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

rand_distr: Use Result instead of panics #770

Merged
merged 6 commits into from
Apr 20, 2019
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 10 additions & 10 deletions benches/distributions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,15 +197,15 @@ distr_float!(distr_openclosed01_f32, f32, OpenClosed01);
distr_float!(distr_openclosed01_f64, f64, OpenClosed01);

// distributions
distr_float!(distr_exp, f64, Exp::new(1.23 * 4.56));
distr_float!(distr_normal, f64, Normal::new(-1.23, 4.56));
distr_float!(distr_log_normal, f64, LogNormal::new(-1.23, 4.56));
distr_float!(distr_gamma_large_shape, f64, Gamma::new(10., 1.0));
distr_float!(distr_gamma_small_shape, f64, Gamma::new(0.1, 1.0));
distr_float!(distr_cauchy, f64, Cauchy::new(4.2, 6.9));
distr_int!(distr_binomial, u64, Binomial::new(20, 0.7));
distr_int!(distr_binomial_small, u64, Binomial::new(1000000, 1e-30));
distr_int!(distr_poisson, u64, Poisson::new(4.0));
distr_float!(distr_exp, f64, Exp::new(1.23 * 4.56).unwrap());
distr_float!(distr_normal, f64, Normal::new(-1.23, 4.56).unwrap());
distr_float!(distr_log_normal, f64, LogNormal::new(-1.23, 4.56).unwrap());
distr_float!(distr_gamma_large_shape, f64, Gamma::new(10., 1.0).unwrap());
distr_float!(distr_gamma_small_shape, f64, Gamma::new(0.1, 1.0).unwrap());
distr_float!(distr_cauchy, f64, Cauchy::new(4.2, 6.9).unwrap());
distr_int!(distr_binomial, u64, Binomial::new(20, 0.7).unwrap());
distr_int!(distr_binomial_small, u64, Binomial::new(1000000, 1e-30).unwrap());
distr_int!(distr_poisson, u64, Poisson::new(4.0).unwrap());
distr!(distr_bernoulli, bool, Bernoulli::new(0.18));
distr_arr!(distr_circle, [f64; 2], UnitCircle::new());
distr_arr!(distr_sphere_surface, [f64; 3], UnitSphereSurface::new());
Expand Down Expand Up @@ -279,7 +279,7 @@ gen_range_float!(gen_range_f64, f64, 123.456f64, 7890.12);
#[bench]
fn dist_iter(b: &mut Bencher) {
let mut rng = SmallRng::from_entropy();
let distr = Normal::new(-2.71828, 3.14159);
let distr = Normal::new(-2.71828, 3.14159).unwrap();
let mut iter = distr.sample_iter(&mut rng);

b.iter(|| {
Expand Down
35 changes: 23 additions & 12 deletions rand_distr/src/binomial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::utils::log_gamma;
/// ```
/// use rand_distr::{Binomial, Distribution};
///
/// let bin = Binomial::new(20, 0.3);
/// let bin = Binomial::new(20, 0.3).unwrap();
/// let v = bin.sample(&mut rand::thread_rng());
/// println!("{} is from a binomial distribution", v);
/// ```
Expand All @@ -35,15 +35,26 @@ pub struct Binomial {
p: f64,
}

/// Error type returned from `Binomial::new`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// `p < 0` or `nan`.
ProbabilityTooSmall,
/// `p > 1`.
ProbabilityTooLarge,
}

impl Binomial {
/// Construct a new `Binomial` with the given shape parameters `n` (number
/// of trials) and `p` (probability of success).
///
/// Panics if `p < 0` or `p > 1`.
pub fn new(n: u64, p: f64) -> Binomial {
assert!(p >= 0.0, "Binomial::new called with p < 0");
assert!(p <= 1.0, "Binomial::new called with p > 1");
Binomial { n, p }
pub fn new(n: u64, p: f64) -> Result<Binomial, Error> {
if !(p >= 0.0) {
return Err(Error::ProbabilityTooSmall);
}
if !(p <= 1.0) {
return Err(Error::ProbabilityTooLarge);
}
Ok(Binomial { n, p })
}
}

Expand Down Expand Up @@ -101,7 +112,7 @@ impl Distribution<u64> for Binomial {

// we use the Cauchy distribution as the comparison distribution
// f(x) ~ 1/(1+x^2)
let cauchy = Cauchy::new(0.0, 1.0);
let cauchy = Cauchy::new(0.0, 1.0).unwrap();
loop {
let mut comp_dev: f64;
loop {
Expand Down Expand Up @@ -148,7 +159,7 @@ mod test {
use super::Binomial;

fn test_binomial_mean_and_variance<R: Rng>(n: u64, p: f64, rng: &mut R) {
let binomial = Binomial::new(n, p);
let binomial = Binomial::new(n, p).unwrap();

let expected_mean = n as f64 * p;
let expected_variance = n as f64 * p * (1.0 - p);
Expand Down Expand Up @@ -178,13 +189,13 @@ mod test {
#[test]
fn test_binomial_end_points() {
let mut rng = crate::test::rng(352);
assert_eq!(rng.sample(Binomial::new(20, 0.0)), 0);
assert_eq!(rng.sample(Binomial::new(20, 1.0)), 20);
assert_eq!(rng.sample(Binomial::new(20, 0.0).unwrap()), 0);
assert_eq!(rng.sample(Binomial::new(20, 1.0).unwrap()), 20);
}

#[test]
#[should_panic]
fn test_binomial_invalid_lambda_neg() {
Binomial::new(20, -10.0);
Binomial::new(20, -10.0).unwrap();
}
}
28 changes: 18 additions & 10 deletions rand_distr/src/cauchy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use std::f64::consts::PI;
/// ```
/// use rand_distr::{Cauchy, Distribution};
///
/// let cau = Cauchy::new(2.0, 5.0);
/// let cau = Cauchy::new(2.0, 5.0).unwrap();
/// let v = cau.sample(&mut rand::thread_rng());
/// println!("{} is from a Cauchy(2, 5) distribution", v);
/// ```
Expand All @@ -33,16 +33,24 @@ pub struct Cauchy {
scale: f64
}

/// Error type returned from `Cauchy::new`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// `scale <= 0` or `nan`.
ScaleTooSmall,
}

impl Cauchy {
/// Construct a new `Cauchy` with the given shape parameters
/// `median` the peak location and `scale` the scale factor.
/// Panics if `scale <= 0`.
pub fn new(median: f64, scale: f64) -> Cauchy {
assert!(scale > 0.0, "Cauchy::new called with scale factor <= 0");
Cauchy {
pub fn new(median: f64, scale: f64) -> Result<Cauchy, Error> {
if !(scale > 0.0) {
return Err(Error::ScaleTooSmall);
}
Ok(Cauchy {
median,
scale
}
})
}
}

Expand Down Expand Up @@ -76,7 +84,7 @@ mod test {

#[test]
fn test_cauchy_median() {
let cauchy = Cauchy::new(10.0, 5.0);
let cauchy = Cauchy::new(10.0, 5.0).unwrap();
let mut rng = crate::test::rng(123);
let mut numbers: [f64; 1000] = [0.0; 1000];
for i in 0..1000 {
Expand All @@ -89,7 +97,7 @@ mod test {

#[test]
fn test_cauchy_mean() {
let cauchy = Cauchy::new(10.0, 5.0);
let cauchy = Cauchy::new(10.0, 5.0).unwrap();
let mut rng = crate::test::rng(123);
let mut sum = 0.0;
for _ in 0..1000 {
Expand All @@ -104,12 +112,12 @@ mod test {
#[test]
#[should_panic]
fn test_cauchy_invalid_scale_zero() {
Cauchy::new(0.0, 0.0);
Cauchy::new(0.0, 0.0).unwrap();
}

#[test]
#[should_panic]
fn test_cauchy_invalid_scale_neg() {
Cauchy::new(0.0, -10.0);
Cauchy::new(0.0, -10.0).unwrap();
}
}
59 changes: 36 additions & 23 deletions rand_distr/src/dirichlet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,47 +25,60 @@ use crate::gamma::Gamma;
/// use rand::prelude::*;
/// use rand_distr::Dirichlet;
///
/// let dirichlet = Dirichlet::new(vec![1.0, 2.0, 3.0]);
/// let dirichlet = Dirichlet::new(vec![1.0, 2.0, 3.0]).unwrap();
/// let samples = dirichlet.sample(&mut rand::thread_rng());
/// println!("{:?} is from a Dirichlet([1.0, 2.0, 3.0]) distribution", samples);
/// ```

#[derive(Clone, Debug)]
pub struct Dirichlet {
/// Concentration parameters (alpha)
alpha: Vec<f64>,
}

/// Error type returned from `Dirchlet::new`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// `alpha.len() < 2`.
AlphaTooShort,
/// `alpha <= 0.0` or `nan`.
AlphaTooSmall,
/// `size < 2`.
SizeTooSmall,
}

impl Dirichlet {
/// Construct a new `Dirichlet` with the given alpha parameter `alpha`.
///
/// # Panics
/// - if `alpha.len() < 2`
vks marked this conversation as resolved.
Show resolved Hide resolved
///
/// Requires `alpha.len() >= 2`.
#[inline]
pub fn new<V: Into<Vec<f64>>>(alpha: V) -> Dirichlet {
pub fn new<V: Into<Vec<f64>>>(alpha: V) -> Result<Dirichlet, Error> {
let a = alpha.into();
assert!(a.len() > 1);
if a.len() < 2 {
return Err(Error::AlphaTooShort);
}
for i in 0..a.len() {
assert!(a[i] > 0.0);
if !(a[i] > 0.0) {
return Err(Error::AlphaTooSmall);
}
}

Dirichlet { alpha: a }
Ok(Dirichlet { alpha: a })
}

/// Construct a new `Dirichlet` with the given shape parameter `alpha` and `size`.
///
/// # Panics
/// - if `alpha <= 0.0`
/// - if `size < 2`
///
/// Requires `size >= 2`.
#[inline]
pub fn new_with_param(alpha: f64, size: usize) -> Dirichlet {
assert!(alpha > 0.0);
assert!(size > 1);
Dirichlet {
alpha: vec![alpha; size],
pub fn new_with_param(alpha: f64, size: usize) -> Result<Dirichlet, Error> {
if !(alpha > 0.0) {
return Err(Error::AlphaTooSmall);
}
if size < 2 {
return Err(Error::SizeTooSmall);
}
Ok(Dirichlet {
alpha: vec![alpha; size],
})
}
}

Expand All @@ -76,7 +89,7 @@ impl Distribution<Vec<f64>> for Dirichlet {
let mut sum = 0.0f64;

for i in 0..n {
let g = Gamma::new(self.alpha[i], 1.0);
let g = Gamma::new(self.alpha[i], 1.0).unwrap();
samples[i] = g.sample(rng);
sum += samples[i];
}
Expand All @@ -95,7 +108,7 @@ mod test {

#[test]
fn test_dirichlet() {
let d = Dirichlet::new(vec![1.0, 2.0, 3.0]);
let d = Dirichlet::new(vec![1.0, 2.0, 3.0]).unwrap();
let mut rng = crate::test::rng(221);
let samples = d.sample(&mut rng);
let _: Vec<f64> = samples
Expand All @@ -111,7 +124,7 @@ mod test {
fn test_dirichlet_with_param() {
let alpha = 0.5f64;
let size = 2;
let d = Dirichlet::new_with_param(alpha, size);
let d = Dirichlet::new_with_param(alpha, size).unwrap();
let mut rng = crate::test::rng(221);
let samples = d.sample(&mut rng);
let _: Vec<f64> = samples
Expand All @@ -126,12 +139,12 @@ mod test {
#[test]
#[should_panic]
fn test_dirichlet_invalid_length() {
Dirichlet::new_with_param(0.5f64, 1);
Dirichlet::new_with_param(0.5f64, 1).unwrap();
}

#[test]
#[should_panic]
fn test_dirichlet_invalid_alpha() {
Dirichlet::new_with_param(0.0f64, 2);
Dirichlet::new_with_param(0.0f64, 2).unwrap();
}
}
25 changes: 17 additions & 8 deletions rand_distr/src/exponential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl Distribution<f64> for Exp1 {
/// ```
/// use rand_distr::{Exp, Distribution};
///
/// let exp = Exp::new(2.0);
/// let exp = Exp::new(2.0).unwrap();
/// let v = exp.sample(&mut rand::thread_rng());
/// println!("{} is from a Exp(2) distribution", v);
/// ```
Expand All @@ -81,13 +81,22 @@ pub struct Exp {
lambda_inverse: f64
}

/// Error type returned from `Exp::new`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// `lambda <= 0` or `nan`.
LambdaTooSmall,
}

impl Exp {
/// Construct a new `Exp` with the given shape parameter
/// `lambda`. Panics if `lambda <= 0`.
/// `lambda`.
#[inline]
pub fn new(lambda: f64) -> Exp {
assert!(lambda > 0.0, "Exp::new called with `lambda` <= 0");
Exp { lambda_inverse: 1.0 / lambda }
pub fn new(lambda: f64) -> Result<Exp, Error> {
if !(lambda > 0.0) {
return Err(Error::LambdaTooSmall);
}
Ok(Exp { lambda_inverse: 1.0 / lambda })
}
}

Expand All @@ -105,7 +114,7 @@ mod test {

#[test]
fn test_exp() {
let exp = Exp::new(10.0);
let exp = Exp::new(10.0).unwrap();
let mut rng = crate::test::rng(221);
for _ in 0..1000 {
assert!(exp.sample(&mut rng) >= 0.0);
Expand All @@ -114,11 +123,11 @@ mod test {
#[test]
#[should_panic]
fn test_exp_invalid_lambda_zero() {
Exp::new(0.0);
Exp::new(0.0).unwrap();
}
#[test]
#[should_panic]
fn test_exp_invalid_lambda_neg() {
Exp::new(-10.0);
Exp::new(-10.0).unwrap();
}
}