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
#![allow(deprecated)]
use crate::Rng;
use crate::distributions::Distribution;
use std::f64::consts::PI;
#[deprecated(since="0.7.0", note="moved to rand_distr crate")]
#[derive(Clone, Copy, Debug)]
pub struct Cauchy {
median: f64,
scale: f64
}
impl Cauchy {
pub fn new(median: f64, scale: f64) -> Cauchy {
assert!(scale > 0.0, "Cauchy::new called with scale factor <= 0");
Cauchy {
median,
scale
}
}
}
impl Distribution<f64> for Cauchy {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
let x = rng.gen::<f64>();
let comp_dev = (PI * x).tan();
let result = self.median + self.scale * comp_dev;
result
}
}
#[cfg(test)]
mod test {
use crate::distributions::Distribution;
use super::Cauchy;
fn median(mut numbers: &mut [f64]) -> f64 {
sort(&mut numbers);
let mid = numbers.len() / 2;
numbers[mid]
}
fn sort(numbers: &mut [f64]) {
numbers.sort_by(|a, b| a.partial_cmp(b).unwrap());
}
#[test]
#[cfg(not(miri))]
fn test_cauchy_averages() {
let cauchy = Cauchy::new(10.0, 5.0);
let mut rng = crate::test::rng(123);
let mut numbers: [f64; 1000] = [0.0; 1000];
let mut sum = 0.0;
for i in 0..1000 {
numbers[i] = cauchy.sample(&mut rng);
sum += numbers[i];
}
let median = median(&mut numbers);
println!("Cauchy median: {}", median);
assert!((median - 10.0).abs() < 0.4);
let mean = sum / 1000.0;
println!("Cauchy mean: {}", mean);
assert!((mean - 10.0).abs() > 0.4);
}
#[test]
#[should_panic]
fn test_cauchy_invalid_scale_zero() {
Cauchy::new(0.0, 0.0);
}
#[test]
#[should_panic]
fn test_cauchy_invalid_scale_neg() {
Cauchy::new(0.0, -10.0);
}
}