Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add p() for Bernoulli #1481

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

marcpabst
Copy link

  • Added a CHANGELOG.md entry

Summary

Add accessor for Bernoulli returning the probbability of true

Motivation

There is currently no way to obtain p.

I'm happy to extend this PR with similiar smale-scale changes for other distributions.

There should be a way to obtain the probability of `true`.
@benjamin-lieser
Copy link
Contributor

This does not compile. From is for lossless and error-less conversions only. If you need to cast a u64 to a f64 you should use as and be aware that you might loose precision, which should be fine in this case.

@marcpabst
Copy link
Author

Oh god, I pushed the wrong commit! Sorry, will push an actually working one later!

@dhardy dhardy added the D-changes Do: changes requested label Aug 12, 2024
@@ -20,6 +20,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.
- Fix portability of `rand::distributions::Slice` (#1469)
- Rename `rand::distributions` to `rand::distr` (#1470)
- The `serde1` feature has been renamed `serde` (#1477)
- Add `p()` for `Bernoulli` to access probability.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please include the PR: #1481

@@ -136,6 +136,16 @@ 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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should note that the output is a reconstruction which may differ from the input to Bernoulli::new.

if self.p_int == ALWAYS_TRUE {
1.0
} else {
f64::from(self.p_int) / SCALE
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since p_int is constructed in new or from_ratio via as cast from f64, we can safely use as to cast back again (there may be some loss of precision, particularly if a very small value were passed into new).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
D-changes Do: changes requested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants