├── .gitignore ├── .github └── workflows │ └── rust.yml ├── Cargo.toml ├── LICENSE-MIT ├── README.md ├── LICENSE-APACHE └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Build 20 | run: cargo build --verbose 21 | - name: Run tests 22 | run: cargo test --verbose 23 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Nick Fitzgerald ", "Jim Blandy "] 3 | categories = ["algorithms", "development-tools", "development-tools::profiling", "mathematics"] 4 | description = "Efficient sampling with uniform probability." 5 | documentation = "https://docs.rs/fast-bernoulli" 6 | license = "MIT OR Apache-2.0" 7 | name = "fast-bernoulli" 8 | readme = "./README.md" 9 | repository = "https://github.com/fitzgen/fast-bernoulli" 10 | version = "1.0.2" 11 | edition = "2021" 12 | 13 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 14 | 15 | [dependencies] 16 | rand = "0.8.5" 17 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2022 Nick Fitzgerald 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

fast-bernoulli

3 |

4 | Efficient sampling with uniform probability 5 |

6 |

7 | 8 | 9 | 10 | 11 |

12 |
13 | 14 | When gathering statistics about a program's behavior, we may be observing events 15 | that occur very frequently (e.g., function calls or memory allocations) and we 16 | may be gathering information that is somewhat expensive to produce (e.g., call 17 | stacks). Sampling all the events could have a significant impact on the 18 | program's performance. 19 | 20 | Why not just sample every `N`'th event? This technique is called "systematic 21 | sampling"; it's simple and efficient, and it's fine if we imagine a patternless 22 | stream of events. But what if we're sampling allocations, and the program 23 | happens to have a loop where each iteration does exactly `N` allocations? You 24 | would end up sampling the same allocation every time through the loop; the 25 | entire rest of the loop becomes invisible to your measurements! More generally, 26 | if each iteration does `M` allocations, and `M` and `N` have any common divisor 27 | at all, most allocation sites will never be sampled. If they're both even, say, 28 | the odd-numbered allocations disappear from your results. 29 | 30 | Ideally, we'd like each event to have some probability `P` of being sampled, 31 | independent of its neighbors and of its position in the sequence. This is called 32 | ["Bernoulli sampling"][bernoulli-sampling], and it doesn't suffer from any of 33 | the problems mentioned above. 34 | 35 | [bernoulli-sampling]: https://en.wikipedia.org/wiki/Bernoulli_sampling 36 | 37 | One disadvantage of Bernoulli sampling is that you can't be sure exactly how 38 | many samples you'll get: technically, it's possible that you might sample none 39 | of them, or all of them. But if the number of events `N` is large, these aren't 40 | likely outcomes; you can generally expect somewhere around `P * N` events to be 41 | sampled. 42 | 43 | The other disadvantage of Bernoulli sampling is that you have to generate a 44 | random number for every event, which can be slow. 45 | 46 | > <significant pause> 47 | 48 | BUT NOT WITH THIS CRATE! 49 | 50 | `FastBernoulli` lets you do true Bernoulli sampling, while generating a fresh 51 | random number only when we do decide to sample an event, not on every 52 | trial. When it decides not to sample, a call to `FastBernoulli::trial` is 53 | nothing but decrementing a counter and comparing it to zero. So the lower your 54 | sampling probability is, the less overhead `FastBernoulli` imposes. 55 | 56 | Finally, probabilities of `0` and `1` are handled efficiently. (In neither case 57 | need we ever generate a random number at all.) 58 | 59 | ## Example 60 | 61 | ```rust 62 | use fast_bernoulli::FastBernoulli; 63 | use rand::Rng; 64 | 65 | // Get the thread-local random number generator. 66 | let mut rng = rand::thread_rng(); 67 | 68 | // Create a `FastBernoulli` instance that samples events with probability 1/20. 69 | let mut bernoulli = FastBernoulli::new(0.05, &mut rng); 70 | 71 | // Each time your event occurs, perform a Bernoulli trail to determine whether 72 | // you should sample the event or not. 73 | let on_my_event = || { 74 | if bernoulli.trial(&mut rng) { 75 | // Record the sample... 76 | } 77 | }; 78 | ``` 79 | 80 | ## Inspiration 81 | 82 | This crate uses the same technique that [Jim Blandy] used for [the 83 | `FastBernoulliTrial` class][firefox-class] in Firefox. This implementation is 84 | not a direct transcription of that C++ to Rust, however I did copy (and lightly 85 | edit) some documentation and comments from the original (for example, most of 86 | this README / crate-level documentation). 87 | 88 | [Jim Blandy]: https://www.red-bean.com/~jimb/ 89 | [firefox-class]: https://searchfox.org/mozilla-central/rev/a6d25de0c706dbc072407ed5d339aaed1cab43b7/mfbt/FastBernoulliTrial.h 90 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | #![deny(missing_debug_implementations, missing_docs)] 3 | #![forbid(unsafe_code)] 4 | 5 | // [What follows is another outstanding comment from Jim Blandy explaining why 6 | // this technique works.] 7 | // 8 | // This comment should just read, "Generate skip counts with a geometric 9 | // distribution", and leave everyone to go look that up and see why it's the 10 | // right thing to do, if they don't know already. 11 | // 12 | // BUT IF YOU'RE CURIOUS, COMMENTS ARE FREE... 13 | // 14 | // Instead of generating a fresh random number for every trial, we can 15 | // randomly generate a count of how many times we should return false before 16 | // the next time we return true. We call this a "skip count". Once we've 17 | // returned true, we generate a fresh skip count, and begin counting down 18 | // again. 19 | // 20 | // Here's an awesome fact: by exercising a little care in the way we generate 21 | // skip counts, we can produce results indistinguishable from those we would 22 | // get "rolling the dice" afresh for every trial. 23 | // 24 | // In short, skip counts in Bernoulli trials of probability `P` obey a geometric 25 | // distribution. If a random variable `X` is uniformly distributed from 26 | // `[0..1)`, then `floor(log(X) / log(1-P))` has the appropriate geometric 27 | // distribution for the skip counts. 28 | // 29 | // Why that formula? 30 | // 31 | // Suppose we're to return `true` with some probability `P`, say, `0.3`. Spread 32 | // all possible futures along a line segment of length `1`. In portion `P` of 33 | // those cases, we'll return true on the next call to `trial`; the skip count is 34 | // 0. For the remaining portion `1-P` of cases, the skip count is `1` or more. 35 | // 36 | // ``` 37 | // skip: 0 1 or more 38 | // |------------------^-----------------------------------------| 39 | // portion: 0.3 0.7 40 | // P 1-P 41 | // ``` 42 | // 43 | // But the "1 or more" section of the line is subdivided the same way: *within 44 | // that section*, in portion `P` the second call to `trial()` returns `true`, and 45 | // in portion `1-P` it returns `false` a second time; the skip count is two or 46 | // more. So we return `true` on the second call in proportion `0.7 * 0.3`, and 47 | // skip at least the first two in proportion `0.7 * 0.7`. 48 | // 49 | // ``` 50 | // skip: 0 1 2 or more 51 | // |------------------^------------^----------------------------| 52 | // portion: 0.3 0.7 * 0.3 0.7 * 0.7 53 | // P (1-P)*P (1-P)^2 54 | // ``` 55 | // 56 | // We can continue to subdivide: 57 | // 58 | // ``` 59 | // skip >= 0: |------------------------------------------------- (1-P)^0 --| 60 | // skip >= 1: | ------------------------------- (1-P)^1 --| 61 | // skip >= 2: | ------------------ (1-P)^2 --| 62 | // skip >= 3: | ^ ---------- (1-P)^3 --| 63 | // skip >= 4: | . --- (1-P)^4 --| 64 | // . 65 | // ^X, see below 66 | // ``` 67 | // 68 | // In other words, the likelihood of the next `n` calls to `trial` returning 69 | // `false` is `(1-P)^n`. The longer a run we require, the more the likelihood 70 | // drops. Further calls may return `false` too, but this is the probability 71 | // we'll skip at least `n`. 72 | // 73 | // This is interesting, because we can pick a point along this line segment and 74 | // see which skip count's range it falls within; the point `X` above, for 75 | // example, is within the ">= 2" range, but not within the ">= 3" range, so it 76 | // designates a skip count of `2`. So if we pick points on the line at random 77 | // and use the skip counts they fall under, that will be indistinguishable from 78 | // generating a fresh random number between `0` and `1` for each trial and 79 | // comparing it to `P`. 80 | // 81 | // So to find the skip count for a point `X`, we must ask: To what whole power 82 | // must we raise `1-P` such that we include `X`, but the next power would 83 | // exclude it? This is exactly `floor(log(X) / log(1-P))`. 84 | // 85 | // Our algorithm is then, simply: When constructed, compute an initial skip 86 | // count. Return `false` from `trial` that many times, and then compute a new 87 | // skip count. 88 | // 89 | // For a call to `multi_trial(n)`, if the skip count is greater than `n`, return 90 | // `false` and subtract `n` from the skip count. If the skip count is less than 91 | // `n`, return true and compute a new skip count. Since each trial is 92 | // independent, it doesn't matter by how much `n` overshoots the skip count; we 93 | // can actually compute a new skip count at *any* time without affecting the 94 | // distribution. This is really beautiful. 95 | 96 | use rand::Rng; 97 | 98 | /// Fast Bernoulli sampling: each event has equal probability of being sampled. 99 | /// 100 | /// See the [crate-level documentation][crate] for more general 101 | /// information. 102 | /// 103 | /// # Example 104 | /// 105 | /// ``` 106 | /// use fast_bernoulli::FastBernoulli; 107 | /// use rand::Rng; 108 | /// 109 | /// // Get the thread-local random number generator. 110 | /// let mut rng = rand::thread_rng(); 111 | /// 112 | /// // Create a `FastBernoulli` instance that samples events with probability 1/20. 113 | /// let mut bernoulli = FastBernoulli::new(0.05, &mut rng); 114 | /// 115 | /// // Each time your event occurs, perform a Bernoulli trail to determine whether 116 | /// // you should sample the event or not. 117 | /// let on_my_event = || { 118 | /// if bernoulli.trial(&mut rng) { 119 | /// // Record the sample... 120 | /// } 121 | /// }; 122 | /// ``` 123 | #[derive(Debug, Clone, Copy)] 124 | pub struct FastBernoulli { 125 | probability: f64, 126 | skip_count: u32, 127 | } 128 | 129 | impl FastBernoulli { 130 | /// Construct a new `FastBernoulli` instance that samples events with the 131 | /// given probability. 132 | /// 133 | /// # Panics 134 | /// 135 | /// The probability must be within the range `0.0 <= probability <= 1.0` and 136 | /// this method will panic if that is not the case. 137 | /// 138 | /// # Example 139 | /// 140 | /// ``` 141 | /// use rand::Rng; 142 | /// use fast_bernoulli::FastBernoulli; 143 | /// 144 | /// let mut rng = rand::thread_rng(); 145 | /// let sample_one_in_a_hundred = FastBernoulli::new(0.01, &mut rng); 146 | /// ``` 147 | pub fn new(probability: f64, rng: &mut R) -> Self 148 | where 149 | R: Rng + ?Sized, 150 | { 151 | assert!( 152 | 0.0 <= probability && probability <= 1.0, 153 | "`probability` must be in the range `0.0 <= probability <= 1.0`" 154 | ); 155 | 156 | let mut bernoulli = FastBernoulli { 157 | probability, 158 | skip_count: 0, 159 | }; 160 | bernoulli.reset_skip_count(rng); 161 | bernoulli 162 | } 163 | 164 | fn reset_skip_count(&mut self, rng: &mut R) 165 | where 166 | R: Rng + ?Sized, 167 | { 168 | if self.probability == 0.0 { 169 | // Edge case: we will never sample any event. 170 | self.skip_count = u32::MAX; 171 | } else if self.probability == 1.0 { 172 | // Edge case: we will sample every event. 173 | self.skip_count = 0; 174 | } else { 175 | // Common case: we need to choose a new skip count using the 176 | // formula `floor(log(x) / log(1 - P))`, as explained in the 177 | // comment at the top of this file. 178 | let x: f64 = rng.gen_range(0.0..1.0); 179 | let skip_count = (x.ln() / (1.0 - self.probability).ln()).floor(); 180 | debug_assert!(skip_count >= 0.0); 181 | self.skip_count = if skip_count <= (u32::MAX as f64) { 182 | skip_count as u32 183 | } else { 184 | // Clamp the skip count to `u32::MAX`. This can skew 185 | // sampling when we are sampling with a very low 186 | // probability, but it is better than any super-robust 187 | // alternative we have, such as representing skip counts 188 | // with big nums. 189 | u32::MAX 190 | }; 191 | } 192 | } 193 | 194 | /// Perform a Bernoulli trial: returns `true` with the configured 195 | /// probability. 196 | /// 197 | /// Call this each time an event occurs to determine whether to sample the 198 | /// event. 199 | /// 200 | /// The lower the configured probability, the less overhead calling this 201 | /// function has. 202 | /// 203 | /// # Example 204 | /// 205 | /// ``` 206 | /// use rand::Rng; 207 | /// use fast_bernoulli::FastBernoulli; 208 | /// 209 | /// let mut rng = rand::thread_rng(); 210 | /// let mut bernoulli = FastBernoulli::new(0.1, &mut rng); 211 | /// 212 | /// // Each time an event occurs, call `trial`... 213 | /// if bernoulli.trial(&mut rng) { 214 | /// // ...and if it returns true, record a sample of this event. 215 | /// } 216 | /// ``` 217 | pub fn trial(&mut self, rng: &mut R) -> bool 218 | where 219 | R: Rng + ?Sized, 220 | { 221 | if self.skip_count > 0 { 222 | self.skip_count -= 1; 223 | return false; 224 | } 225 | 226 | self.reset_skip_count(rng); 227 | self.probability != 0.0 228 | } 229 | 230 | /// Perform `n` Bernoulli trials at once. 231 | /// 232 | /// This is semantically equivalent to calling the `trial()` method `n` 233 | /// times and returning `true` if any of those calls returned `true`, but 234 | /// runs in `O(1)` time instead of `O(n)` time. 235 | /// 236 | /// What is this good for? In some applications, some events are "bigger" 237 | /// than others. For example, large memory allocations are more significant 238 | /// than small memory allocations. Perhaps we'd like to imagine that we're 239 | /// drawing allocations from a stream of bytes, and performing a separate 240 | /// Bernoulli trial on every byte from the stream. We can accomplish this by 241 | /// calling `multi_trial(s)` for the number of bytes `s`, and sampling the 242 | /// event if that call returns true. 243 | /// 244 | /// Of course, this style of sampling needs to be paired with analysis and 245 | /// presentation that makes the "size" of the event apparent, lest trials 246 | /// with large values for `n` appear to be indistinguishable from those with 247 | /// small values for `n`, despite being potentially much more likely to be 248 | /// sampled. 249 | /// 250 | /// # Example 251 | /// 252 | /// ``` 253 | /// use rand::Rng; 254 | /// use fast_bernoulli::FastBernoulli; 255 | /// 256 | /// let mut rng = rand::thread_rng(); 257 | /// let mut byte_sampler = FastBernoulli::new(0.05, &mut rng); 258 | /// 259 | /// // When we observe a `malloc` of ten bytes event... 260 | /// if byte_sampler.multi_trial(10, &mut rng) { 261 | /// // ... if `multi_trial` returns `true` then we sample it. 262 | /// record_malloc_sample(10); 263 | /// } 264 | /// 265 | /// // And when we observe a `malloc` of 1024 bytes event... 266 | /// if byte_sampler.multi_trial(1024, &mut rng) { 267 | /// // ... if `multi_trial` returns `true` then we sample this larger 268 | /// // allocation. 269 | /// record_malloc_sample(1024); 270 | /// } 271 | /// # fn record_malloc_sample(_: u32) {} 272 | /// ``` 273 | pub fn multi_trial(&mut self, n: u32, rng: &mut R) -> bool 274 | where 275 | R: Rng + ?Sized, 276 | { 277 | if n < self.skip_count { 278 | self.skip_count -= n; 279 | return false; 280 | } 281 | 282 | self.reset_skip_count(rng); 283 | self.probability != 0.0 284 | } 285 | 286 | /// Get the probability with which events are sampled. 287 | /// 288 | /// This is a number between `0.0` and `1.0`. 289 | /// 290 | /// This is the same value that was passed to `FastBernoulli::new` when 291 | /// constructing this instance. 292 | #[inline] 293 | pub fn probability(&self) -> f64 { 294 | self.probability 295 | } 296 | 297 | /// How many events will be skipped until the next event is sampled? 298 | /// 299 | /// When `self.probability() == 0.0` this method's return value is 300 | /// inaccurate, and logically should be infinity. 301 | /// 302 | /// # Example 303 | /// 304 | /// ``` 305 | /// use rand::Rng; 306 | /// use fast_bernoulli::FastBernoulli; 307 | /// 308 | /// let mut rng = rand::thread_rng(); 309 | /// let mut bernoulli = FastBernoulli::new(0.1, &mut rng); 310 | /// 311 | /// // Get the number of upcoming events that will not be sampled. 312 | /// let skip_count = bernoulli.skip_count(); 313 | /// 314 | /// // That many events will not be sampled. 315 | /// for _ in 0..skip_count { 316 | /// assert!(!bernoulli.trial(&mut rng)); 317 | /// } 318 | /// 319 | /// // The next event will be sampled. 320 | /// assert!(bernoulli.trial(&mut rng)); 321 | /// ``` 322 | #[inline] 323 | pub fn skip_count(&self) -> u32 { 324 | self.skip_count 325 | } 326 | } 327 | 328 | #[cfg(test)] 329 | mod tests { 330 | use super::*; 331 | 332 | #[test] 333 | fn expected_number_of_samples() { 334 | let mut rng = rand::thread_rng(); 335 | 336 | let probability = 0.01; 337 | let events = 10_000; 338 | let expected = (events as f64) * probability; 339 | let error_tolerance = expected * 0.25; 340 | 341 | let mut bernoulli = FastBernoulli::new(probability, &mut rng); 342 | 343 | let mut num_sampled = 0; 344 | for _ in 0..events { 345 | if bernoulli.trial(&mut rng) { 346 | num_sampled += 1; 347 | } 348 | } 349 | 350 | let min = (expected - error_tolerance) as u32; 351 | let max = (expected + error_tolerance) as u32; 352 | assert!( 353 | min <= num_sampled && num_sampled <= max, 354 | "expected ~{} samples, found {} (acceptable range is {} to {})", 355 | expected, 356 | num_sampled, 357 | min, 358 | max, 359 | ); 360 | } 361 | } 362 | --------------------------------------------------------------------------------