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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
|
import math
import rand
import rand.dist
const (
// The sample size to be used
count = 2000
// Accepted error is within 5% of the actual values.
error = 0.05
// The seeds used (for reproducible testing)
seeds = [[u32(0xffff24), 0xabcd], [u32(0x141024), 0x42851],
[u32(0x1452), 0x90cd],
]
)
fn test_bernoulli() {
ps := [0.0, 0.1, 1.0 / 3.0, 0.5, 0.8, 17.0 / 18.0, 1.0]
for seed in seeds {
rand.seed(seed)
for p in ps {
mut successes := 0
for _ in 0 .. count {
if dist.bernoulli(p) {
successes++
}
}
assert math.abs(f64(successes) / count - p) < error
}
}
}
fn test_binomial() {
ns := [100, 200, 1000]
ps := [0.0, 0.5, 0.95, 1.0]
for seed in seeds {
rand.seed(seed)
for n in ns {
for p in ps {
np := n * p
npq := np * (1 - p)
mut sum := 0
mut var := 0.0
for _ in 0 .. count {
x := dist.binomial(n, p)
sum += x
dist := (x - np)
var += dist * dist
}
assert math.abs(f64(sum / count) - np) / n < error
assert math.abs(f64(var / count) - npq) / n < error
}
}
}
}
fn test_normal_pair() {
mus := [0, 10, 100, -40]
sigmas := [1, 2, 40, 5]
total := 2 * count
for seed in seeds {
rand.seed(seed)
for mu in mus {
for sigma in sigmas {
mut sum := 0.0
mut var := 0.0
for _ in 0 .. count {
x, y := dist.normal_pair(mu: mu, sigma: sigma)
sum += x + y
dist_x := x - mu
dist_y := y - mu
var += dist_x * dist_x
var += dist_y * dist_y
}
variance := sigma * sigma
assert math.abs(f64(sum / total) - mu) / sigma < 1
assert math.abs(f64(var / total) - variance) / variance < 2 * error
}
}
}
}
fn test_normal() {
mus := [0, 10, 100, -40, 20]
sigmas := [1, 2, 5]
for seed in seeds {
rand.seed(seed)
for mu in mus {
for sigma in sigmas {
mut sum := 0.0
mut var := 0.0
for _ in 0 .. count {
x := dist.normal(mu: mu, sigma: sigma)
sum += x
dist := x - mu
var += dist * dist
}
variance := sigma * sigma
assert math.abs(f64(sum / count) - mu) / sigma < 1
assert math.abs(f64(var / count) - variance) / variance < 2 * error
}
}
}
}
fn test_exponential() {
lambdas := [1.0, 10, 1 / 20.0, 1 / 10000.0, 1 / 524.0, 200]
for seed in seeds {
rand.seed(seed)
for lambda in lambdas {
mu := 1 / lambda
variance := mu * mu
mut sum := 0.0
mut var := 0.0
for _ in 0 .. count {
x := dist.exponential(lambda)
sum += x
dist := x - mu
var += dist * dist
}
assert math.abs((f64(sum / count) - mu) / mu) < error
assert math.abs((f64(var / count) - variance) / variance) < 2 * error
}
}
}
|