Skip to content

Commit

Permalink
Add p() for Bernoulli (#1481)
Browse files Browse the repository at this point in the history
Co-authored-by: Diggory Hardy <[email protected]>
  • Loading branch information
marcpabst and dhardy authored Oct 17, 2024
1 parent 8225d94 commit 8b455dd
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.
- Rename `rand::distributions` to `rand::distr` (#1470)
- The `serde1` feature has been renamed `serde` (#1477)
- Mark `WeightError`, `PoissonError`, `BinomialError` as `#[non_exhaustive]` (#1480).
- Add `p()` for `Bernoulli` to access probability (#1481)
- Add `UniformUsize` and use to make `Uniform` for `usize` portable (#1487)
- Remove support for generating `isize` and `usize` values with `Standard`, `Uniform` and `Fill` and usage as a `WeightedAliasIndex` weight (#1487)
- Require `Clone` and `AsRef` bound for `SeedableRng::Seed`. (#1491)
Expand Down
12 changes: 12 additions & 0 deletions src/distr/bernoulli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,18 @@ impl Bernoulli {
let p_int = ((f64::from(numerator) / f64::from(denominator)) * SCALE) as u64;
Ok(Bernoulli { p_int })
}

#[inline]
/// Returns the probability (`p`) of the distribution.
///
/// This value may differ slightly from the input due to loss of precision.
pub fn p(&self) -> f64 {
if self.p_int == ALWAYS_TRUE {
1.0
} else {
(self.p_int as f64) / SCALE
}
}
}

impl Distribution<bool> for Bernoulli {
Expand Down

0 comments on commit 8b455dd

Please sign in to comment.