Skip to content

Commit

Permalink
add Default for Uniform, plus unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
avhz authored and avhz committed Aug 4, 2024
1 parent 1a69c5e commit 591c8b3
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions src/distribution/uniform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{Result, StatsError};
use rand::distributions::Uniform as RandUniform;
use rand::Rng;
use std::f64;
use std::fmt::Debug;

/// Implements the [Continuous
/// Uniform](https://en.wikipedia.org/wiki/Uniform_distribution_(continuous))
Expand Down Expand Up @@ -62,7 +63,7 @@ impl Uniform {
}
}

/// Constructs a new standard uniform distribution with
/// Constructs a new standard uniform distribution with
/// a lower bound 0 and an upper bound of 1.
///
/// # Examples
Expand All @@ -73,10 +74,13 @@ impl Uniform {
/// let uniform = Uniform::standard();
/// ```
pub fn standard() -> Self {
Self {
min: 0.0,
max: 1.0,
}
Self { min: 0.0, max: 1.0 }
}
}

impl Default for Uniform {
fn default() -> Self {
Self::standard()
}
}

Expand Down Expand Up @@ -514,4 +518,17 @@ mod tests {
.all(|v| (min <= v) && (v < max))
);
}

#[test]
fn test_default() {
let n = Uniform::default();

let n_mean = n.mean().unwrap();
let n_std = n.std_dev().unwrap();

// Check that the mean of the distribution is close to 1 / 2
assert_almost_eq!(n_mean, 0.5, 1e-15);
// Check that the standard deviation of the distribution is close to 1 / sqrt(12)
assert_almost_eq!(n_std, 0.288_675_134_594_812_9, 1e-15);
}
}

0 comments on commit 591c8b3

Please sign in to comment.