rand_extra/
lib.rs

1//! Random number generation
2
3extern crate rand;
4extern crate num_complex;
5
6use std::marker::PhantomData;
7use rand::Rng;
8use rand::distributions::*;
9use num_complex::Complex;
10
11/// Normal distribution for real numbers
12#[derive(Clone, Copy)]
13pub struct RealNormal<A> {
14    dist: Normal,
15    phantom: PhantomData<A>,
16}
17
18impl<A> RealNormal<A> {
19    pub fn new(center: f64, var: f64) -> Self {
20        RealNormal {
21            dist: Normal::new(center, var),
22            phantom: PhantomData,
23        }
24    }
25}
26
27macro_rules! impl_RealNormal {
28    ($float:ty) => {
29impl Sample<$float> for RealNormal<$float> {
30    fn sample<R>(&mut self, rng: &mut R) -> $float
31        where R: Rng
32    {
33        self.dist.sample(rng) as $float
34    }
35}
36
37impl IndependentSample<$float> for RealNormal<$float> {
38    fn ind_sample<R>(&self, rng: &mut R) -> $float
39        where R: Rng
40    {
41        self.dist.ind_sample(rng) as $float
42    }
43}
44}} // impl_RealNormal
45
46impl_RealNormal!(f64);
47impl_RealNormal!(f32);
48
49/// Normal distribution for complex numbers
50#[derive(Clone, Copy)]
51pub struct ComplexNormal<A> {
52    re_dist: Normal,
53    im_dist: Normal,
54    phantom: PhantomData<A>,
55}
56
57impl<A> ComplexNormal<A> {
58    pub fn new(re0: f64, im0: f64, re_var: f64, im_var: f64) -> Self {
59        ComplexNormal {
60            re_dist: Normal::new(re0, re_var),
61            im_dist: Normal::new(im0, im_var),
62            phantom: PhantomData,
63        }
64    }
65}
66
67macro_rules! impl_ComplexNormal {
68    ($float:ty) => {
69impl Sample<Complex<$float>> for ComplexNormal<$float> {
70    fn sample<R>(&mut self, rng: &mut R) -> Complex<$float>
71        where R: Rng
72    {
73        let re = self.re_dist.sample(rng) as $float;
74        let im = self.im_dist.sample(rng) as $float;
75        Complex::new(re, im)
76    }
77}
78
79impl IndependentSample<Complex<$float>> for ComplexNormal<$float> {
80    fn ind_sample<R>(&self, rng: &mut R) -> Complex<$float>
81        where R: Rng
82    {
83        let re = self.re_dist.ind_sample(rng) as $float;
84        let im = self.im_dist.ind_sample(rng) as $float;
85        Complex::new(re, im)
86    }
87}
88}} // impl_ComplexNormal
89
90impl_ComplexNormal!(f32);
91impl_ComplexNormal!(f64);