ndarray_numtest/
random.rs

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