Skip to content

Commit 8e3ed11

Browse files
committed
impl Distribution<f32> for Exp1 and Exp
1 parent 59bc4d2 commit 8e3ed11

File tree

2 files changed

+24
-11
lines changed

2 files changed

+24
-11
lines changed

rand_distr/src/exponential.rs

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
use rand::Rng;
1313
use crate::{ziggurat_tables, Distribution};
1414
use crate::utils::ziggurat;
15+
use num_traits::Float;
1516

1617
/// Samples floating-point numbers according to the exponential distribution,
1718
/// with rate parameter `λ = 1`. This is equivalent to `Exp::new(1.0)` or
@@ -39,6 +40,15 @@ use crate::utils::ziggurat;
3940
#[derive(Clone, Copy, Debug)]
4041
pub struct Exp1;
4142

43+
impl Distribution<f32> for Exp1 {
44+
#[inline]
45+
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f32 {
46+
// TODO: use optimal 32-bit implementation
47+
let x: f64 = self.sample(rng);
48+
x as f32
49+
}
50+
}
51+
4252
// This could be done via `-rng.gen::<f64>().ln()` but that is slower.
4353
impl Distribution<f64> for Exp1 {
4454
#[inline]
@@ -76,9 +86,9 @@ impl Distribution<f64> for Exp1 {
7686
/// println!("{} is from a Exp(2) distribution", v);
7787
/// ```
7888
#[derive(Clone, Copy, Debug)]
79-
pub struct Exp {
89+
pub struct Exp<N> {
8090
/// `lambda` stored as `1/lambda`, since this is what we scale by.
81-
lambda_inverse: f64
91+
lambda_inverse: N
8292
}
8393

8494
/// Error type returned from `Exp::new`.
@@ -88,22 +98,25 @@ pub enum Error {
8898
LambdaTooSmall,
8999
}
90100

91-
impl Exp {
101+
impl<N: Float> Exp<N>
102+
where Exp1: Distribution<N>
103+
{
92104
/// Construct a new `Exp` with the given shape parameter
93105
/// `lambda`.
94106
#[inline]
95-
pub fn new(lambda: f64) -> Result<Exp, Error> {
96-
if !(lambda > 0.0) {
107+
pub fn new(lambda: N) -> Result<Exp<N>, Error> {
108+
if !(lambda > N::zero()) {
97109
return Err(Error::LambdaTooSmall);
98110
}
99-
Ok(Exp { lambda_inverse: 1.0 / lambda })
111+
Ok(Exp { lambda_inverse: N::one() / lambda })
100112
}
101113
}
102114

103-
impl Distribution<f64> for Exp {
104-
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
105-
let n: f64 = rng.sample(Exp1);
106-
n * self.lambda_inverse
115+
impl<N: Float> Distribution<N> for Exp<N>
116+
where Exp1: Distribution<N>
117+
{
118+
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> N {
119+
rng.sample(Exp1) * self.lambda_inverse
107120
}
108121
}
109122

rand_distr/src/gamma.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ pub enum Error {
6565
#[derive(Clone, Copy, Debug)]
6666
enum GammaRepr {
6767
Large(GammaLargeShape),
68-
One(Exp),
68+
One(Exp<f64>),
6969
Small(GammaSmallShape)
7070
}
7171

0 commit comments

Comments
 (0)