1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
use crate::Complex;
use num_traits::Num;
use rand::distributions::Standard;
use rand::prelude::*;
impl<T> Distribution<Complex<T>> for Standard
where
T: Num + Clone,
Standard: Distribution<T>,
{
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Complex<T> {
Complex::new(self.sample(rng), self.sample(rng))
}
}
#[derive(Clone, Copy, Debug)]
pub struct ComplexDistribution<Re, Im = Re> {
re: Re,
im: Im,
}
impl<Re, Im> ComplexDistribution<Re, Im> {
pub fn new(re: Re, im: Im) -> Self {
ComplexDistribution { re, im }
}
}
impl<T, Re, Im> Distribution<Complex<T>> for ComplexDistribution<Re, Im>
where
T: Num + Clone,
Re: Distribution<T>,
Im: Distribution<T>,
{
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Complex<T> {
Complex::new(self.re.sample(rng), self.im.sample(rng))
}
}
#[cfg(test)]
fn test_rng() -> StdRng {
StdRng::from_seed([42; 32])
}
#[test]
fn standard_f64() {
let mut rng = test_rng();
for _ in 0..100 {
let c: Complex<f64> = rng.gen();
assert!(c.re >= 0.0 && c.re < 1.0);
assert!(c.im >= 0.0 && c.im < 1.0);
}
}
#[test]
fn generic_standard_f64() {
let mut rng = test_rng();
let dist = ComplexDistribution::new(Standard, Standard);
for _ in 0..100 {
let c: Complex<f64> = rng.sample(&dist);
assert!(c.re >= 0.0 && c.re < 1.0);
assert!(c.im >= 0.0 && c.im < 1.0);
}
}
#[test]
fn generic_uniform_f64() {
use rand::distributions::Uniform;
let mut rng = test_rng();
let re = Uniform::new(-100.0, 0.0);
let im = Uniform::new(0.0, 100.0);
let dist = ComplexDistribution::new(re, im);
for _ in 0..100 {
let c = rng.sample(&dist);
assert!(c.re >= -100.0 && c.re < 0.0);
assert!(c.im >= 0.0 && c.im < 100.0);
}
}
#[test]
fn generic_mixed_f64() {
use rand::distributions::Uniform;
let mut rng = test_rng();
let re = Uniform::new(-100.0, 0.0);
let dist = ComplexDistribution::new(re, Standard);
for _ in 0..100 {
let c = rng.sample(&dist);
assert!(c.re >= -100.0 && c.re < 0.0);
assert!(c.im >= 0.0 && c.im < 1.0);
}
}
#[test]
fn generic_uniform_i32() {
use rand::distributions::Uniform;
let mut rng = test_rng();
let re = Uniform::new(-100, 0);
let im = Uniform::new(0, 100);
let dist = ComplexDistribution::new(re, im);
for _ in 0..100 {
let c = rng.sample(&dist);
assert!(c.re >= -100 && c.re < 0);
assert!(c.im >= 0 && c.im < 100);
}
}