Skip to content

Commit 7f56d4e

Browse files
authored
Merge pull request #803 from vks/bernoulli-no-panic
Make `Bernoulli::new` return a `Result`
2 parents 73ef869 + c6bce2c commit 7f56d4e

File tree

5 files changed

+28
-28
lines changed

5 files changed

+28
-28
lines changed

benches/distributions.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ distr_float!(distr_triangular, f64, Triangular::new(0., 1., 0.9).unwrap());
206206
distr_int!(distr_binomial, u64, Binomial::new(20, 0.7).unwrap());
207207
distr_int!(distr_binomial_small, u64, Binomial::new(1000000, 1e-30).unwrap());
208208
distr_int!(distr_poisson, u64, Poisson::new(4.0).unwrap());
209-
distr!(distr_bernoulli, bool, Bernoulli::new(0.18));
209+
distr!(distr_bernoulli, bool, Bernoulli::new(0.18).unwrap());
210210
distr_arr!(distr_circle, [f64; 2], UnitCircle);
211211
distr_arr!(distr_sphere, [f64; 3], UnitSphere);
212212

benches/misc.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ fn misc_gen_ratio_var(b: &mut Bencher) {
7272
fn misc_bernoulli_const(b: &mut Bencher) {
7373
let mut rng = StdRng::from_rng(&mut thread_rng()).unwrap();
7474
b.iter(|| {
75-
let d = rand::distributions::Bernoulli::new(0.18);
75+
let d = rand::distributions::Bernoulli::new(0.18).unwrap();
7676
let mut accum = true;
7777
for _ in 0..::RAND_BENCH_N {
7878
accum ^= rng.sample(d);
@@ -88,7 +88,7 @@ fn misc_bernoulli_var(b: &mut Bencher) {
8888
let mut accum = true;
8989
let mut p = 0.18;
9090
for _ in 0..::RAND_BENCH_N {
91-
let d = Bernoulli::new(p);
91+
let d = Bernoulli::new(p).unwrap();
9292
accum ^= rng.sample(d);
9393
p += 0.0001;
9494
}

src/distributions/bernoulli.rs

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use distributions::Distribution;
2020
/// ```rust
2121
/// use rand::distributions::{Bernoulli, Distribution};
2222
///
23-
/// let d = Bernoulli::new(0.3);
23+
/// let d = Bernoulli::new(0.3).unwrap();
2424
/// let v = d.sample(&mut rand::thread_rng());
2525
/// println!("{} is from a Bernoulli distribution", v);
2626
/// ```
@@ -61,13 +61,16 @@ const ALWAYS_TRUE: u64 = ::core::u64::MAX;
6161
// in `no_std` mode.
6262
const SCALE: f64 = 2.0 * (1u64 << 63) as f64;
6363

64+
/// Error type returned from `Bernoulli::new`.
65+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66+
pub enum BernoulliError {
67+
/// `p < 0` or `p > 1`.
68+
InvalidProbability,
69+
}
70+
6471
impl Bernoulli {
6572
/// Construct a new `Bernoulli` with the given probability of success `p`.
6673
///
67-
/// # Panics
68-
///
69-
/// If `p < 0` or `p > 1`.
70-
///
7174
/// # Precision
7275
///
7376
/// For `p = 1.0`, the resulting distribution will always generate true.
@@ -77,12 +80,12 @@ impl Bernoulli {
7780
/// a multiple of 2<sup>-64</sup>. (Note that not all multiples of
7881
/// 2<sup>-64</sup> in `[0, 1]` can be represented as a `f64`.)
7982
#[inline]
80-
pub fn new(p: f64) -> Bernoulli {
83+
pub fn new(p: f64) -> Result<Bernoulli, BernoulliError> {
8184
if p < 0.0 || p >= 1.0 {
82-
if p == 1.0 { return Bernoulli { p_int: ALWAYS_TRUE } }
83-
panic!("Bernoulli::new not called with 0.0 <= p <= 1.0");
85+
if p == 1.0 { return Ok(Bernoulli { p_int: ALWAYS_TRUE }) }
86+
return Err(BernoulliError::InvalidProbability);
8487
}
85-
Bernoulli { p_int: (p * SCALE) as u64 }
88+
Ok(Bernoulli { p_int: (p * SCALE) as u64 })
8689
}
8790

8891
/// Construct a new `Bernoulli` with the probability of success of
@@ -91,19 +94,16 @@ impl Bernoulli {
9194
///
9295
/// If `numerator == denominator` then the returned `Bernoulli` will always
9396
/// return `true`. If `numerator == 0` it will always return `false`.
94-
///
95-
/// # Panics
96-
///
97-
/// If `denominator == 0` or `numerator > denominator`.
98-
///
9997
#[inline]
100-
pub fn from_ratio(numerator: u32, denominator: u32) -> Bernoulli {
101-
assert!(numerator <= denominator);
98+
pub fn from_ratio(numerator: u32, denominator: u32) -> Result<Bernoulli, BernoulliError> {
99+
if !(numerator <= denominator) {
100+
return Err(BernoulliError::InvalidProbability);
101+
}
102102
if numerator == denominator {
103-
return Bernoulli { p_int: ::core::u64::MAX }
103+
return Ok(Bernoulli { p_int: ALWAYS_TRUE })
104104
}
105105
let p_int = ((numerator as f64 / denominator as f64) * SCALE) as u64;
106-
Bernoulli { p_int }
106+
Ok(Bernoulli { p_int })
107107
}
108108
}
109109

@@ -126,8 +126,8 @@ mod test {
126126
#[test]
127127
fn test_trivial() {
128128
let mut r = ::test::rng(1);
129-
let always_false = Bernoulli::new(0.0);
130-
let always_true = Bernoulli::new(1.0);
129+
let always_false = Bernoulli::new(0.0).unwrap();
130+
let always_true = Bernoulli::new(1.0).unwrap();
131131
for _ in 0..5 {
132132
assert_eq!(r.sample::<bool, _>(&always_false), false);
133133
assert_eq!(r.sample::<bool, _>(&always_true), true);
@@ -142,8 +142,8 @@ mod test {
142142
const P: f64 = 0.3;
143143
const NUM: u32 = 3;
144144
const DENOM: u32 = 10;
145-
let d1 = Bernoulli::new(P);
146-
let d2 = Bernoulli::from_ratio(NUM, DENOM);
145+
let d1 = Bernoulli::new(P).unwrap();
146+
let d2 = Bernoulli::from_ratio(NUM, DENOM).unwrap();
147147
const N: u32 = 100_000;
148148

149149
let mut sum1: u32 = 0;

src/distributions/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ use Rng;
108108
pub use self::other::Alphanumeric;
109109
#[doc(inline)] pub use self::uniform::Uniform;
110110
pub use self::float::{OpenClosed01, Open01};
111-
pub use self::bernoulli::Bernoulli;
111+
pub use self::bernoulli::{Bernoulli, BernoulliError};
112112
#[cfg(feature="alloc")] pub use self::weighted::{WeightedIndex, WeightedError};
113113

114114
// The following are all deprecated after being moved to rand_distr

src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ pub trait Rng: RngCore {
325325
/// [`Bernoulli`]: distributions::bernoulli::Bernoulli
326326
#[inline]
327327
fn gen_bool(&mut self, p: f64) -> bool {
328-
let d = distributions::Bernoulli::new(p);
328+
let d = distributions::Bernoulli::new(p).unwrap();
329329
self.sample(d)
330330
}
331331

@@ -354,7 +354,7 @@ pub trait Rng: RngCore {
354354
/// [`Bernoulli`]: distributions::bernoulli::Bernoulli
355355
#[inline]
356356
fn gen_ratio(&mut self, numerator: u32, denominator: u32) -> bool {
357-
let d = distributions::Bernoulli::from_ratio(numerator, denominator);
357+
let d = distributions::Bernoulli::from_ratio(numerator, denominator).unwrap();
358358
self.sample(d)
359359
}
360360
}

0 commit comments

Comments
 (0)