Debian Codegraph @

rand/rand_test.go

raw symbols SCIP
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package rand
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "io"
12 "math"
13 "os"
14 "runtime"
15 "testing"
16 "testing/iotest"
17 "time"
18 )
19
20 const (
21 numTestSamples = 10000
22 )
23
24 type statsResults struct {
25 mean float64
26 stddev float64
27 closeEnough float64
28 maxError float64
29 }
30
31 func nearEqual(a, b, closeEnough, maxError float64) bool {
32 absDiff := math.Abs(a - b)
33 if absDiff < closeEnough { // Necessary when one value is zero and one value is close to zero.
34 return true
35 }
36 return absDiff/max(math.Abs(a), math.Abs(b)) < maxError
37 }
38
39 var testSeeds = []uint64{1, 1754801282, 1698661970, 1550503961}
40
41 // checkSimilarDistribution returns success if the mean and stddev of the
42 // two statsResults are similar.
43 func (this *statsResults) checkSimilarDistribution(expected *statsResults) error {
44 if !nearEqual(this.mean, expected.mean, expected.closeEnough, expected.maxError) {
45 s := fmt.Sprintf("mean %v != %v (allowed error %v, %v)", this.mean, expected.mean, expected.closeEnough, expected.maxError)
46 fmt.Println(s)
47 return errors.New(s)
48 }
49 if !nearEqual(this.stddev, expected.stddev, 0, expected.maxError) {
50 s := fmt.Sprintf("stddev %v != %v (allowed error %v, %v)", this.stddev, expected.stddev, expected.closeEnough, expected.maxError)
51 fmt.Println(s)
52 return errors.New(s)
53 }
54 return nil
55 }
56
57 func getStatsResults(samples []float64) *statsResults {
58 res := new(statsResults)
59 var sum, squaresum float64
60 for _, s := range samples {
61 sum += s
62 squaresum += s * s
63 }
64 res.mean = sum / float64(len(samples))
65 res.stddev = math.Sqrt(squaresum/float64(len(samples)) - res.mean*res.mean)
66 return res
67 }
68
69 func checkSampleDistribution(t *testing.T, samples []float64, expected *statsResults) {
70 t.Helper()
71 actual := getStatsResults(samples)
72 err := actual.checkSimilarDistribution(expected)
73 if err != nil {
74 t.Error(err)
75 }
76 }
77
78 func checkSampleSliceDistributions(t *testing.T, samples []float64, nslices int, expected *statsResults) {
79 t.Helper()
80 chunk := len(samples) / nslices
81 for i := 0; i < nslices; i++ {
82 low := i * chunk
83 var high int
84 if i == nslices-1 {
85 high = len(samples) - 1
86 } else {
87 high = (i + 1) * chunk
88 }
89 checkSampleDistribution(t, samples[low:high], expected)
90 }
91 }
92
93 //
94 // Normal distribution tests
95 //
96
97 func generateNormalSamples(nsamples int, mean, stddev float64, seed uint64) []float64 {
98 r := New(NewSource(seed))
99 samples := make([]float64, nsamples)
100 for i := range samples {
101 samples[i] = r.NormFloat64()*stddev + mean
102 }
103 return samples
104 }
105
106 func testNormalDistribution(t *testing.T, nsamples int, mean, stddev float64, seed uint64) {
107 //fmt.Printf("testing nsamples=%v mean=%v stddev=%v seed=%v\n", nsamples, mean, stddev, seed);
108
109 samples := generateNormalSamples(nsamples, mean, stddev, seed)
110 errorScale := max(1.0, stddev) // Error scales with stddev
111 expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.08 * errorScale}
112
113 // Make sure that the entire set matches the expected distribution.
114 checkSampleDistribution(t, samples, expected)
115
116 // Make sure that each half of the set matches the expected distribution.
117 checkSampleSliceDistributions(t, samples, 2, expected)
118
119 // Make sure that each 7th of the set matches the expected distribution.
120 checkSampleSliceDistributions(t, samples, 7, expected)
121 }
122
123 // Actual tests
124
125 func TestStandardNormalValues(t *testing.T) {
126 for _, seed := range testSeeds {
127 testNormalDistribution(t, numTestSamples, 0, 1, seed)
128 }
129 }
130
131 func TestNonStandardNormalValues(t *testing.T) {
132 sdmax := 1000.0
133 mmax := 1000.0
134 if testing.Short() {
135 sdmax = 5
136 mmax = 5
137 }
138 for sd := 0.5; sd < sdmax; sd *= 2 {
139 for m := 0.5; m < mmax; m *= 2 {
140 for _, seed := range testSeeds {
141 testNormalDistribution(t, numTestSamples, m, sd, seed)
142 if testing.Short() {
143 break
144 }
145 }
146 }
147 }
148 }
149
150 //
151 // Exponential distribution tests
152 //
153
154 func generateExponentialSamples(nsamples int, rate float64, seed uint64) []float64 {
155 r := New(NewSource(seed))
156 samples := make([]float64, nsamples)
157 for i := range samples {
158 samples[i] = r.ExpFloat64() / rate
159 }
160 return samples
161 }
162
163 func testExponentialDistribution(t *testing.T, nsamples int, rate float64, seed uint64) {
164 //fmt.Printf("testing nsamples=%v rate=%v seed=%v\n", nsamples, rate, seed)
165
166 mean := 1 / rate
167 stddev := mean
168
169 samples := generateExponentialSamples(nsamples, rate, seed)
170 errorScale := max(1.0, 1/rate) // Error scales with the inverse of the rate
171 expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.20 * errorScale}
172
173 // Make sure that the entire set matches the expected distribution.
174 checkSampleDistribution(t, samples, expected)
175
176 // Make sure that each half of the set matches the expected distribution.
177 checkSampleSliceDistributions(t, samples, 2, expected)
178
179 // Make sure that each 7th of the set matches the expected distribution.
180 checkSampleSliceDistributions(t, samples, 7, expected)
181 }
182
183 // Actual tests
184
185 func TestStandardExponentialValues(t *testing.T) {
186 for _, seed := range testSeeds {
187 testExponentialDistribution(t, numTestSamples, 1, seed)
188 }
189 }
190
191 func TestNonStandardExponentialValues(t *testing.T) {
192 for rate := 0.05; rate < 10; rate *= 2 {
193 for _, seed := range testSeeds {
194 testExponentialDistribution(t, numTestSamples, rate, seed)
195 if testing.Short() {
196 break
197 }
198 }
199 }
200 }
201
202 //
203 // Table generation tests
204 //
205
206 func initNorm() (testKn []uint32, testWn, testFn []float32) {
207 const m1 = 1 << 31
208 var (
209 dn float64 = rn
210 tn = dn
211 vn float64 = 9.91256303526217e-3
212 )
213
214 testKn = make([]uint32, 128)
215 testWn = make([]float32, 128)
216 testFn = make([]float32, 128)
217
218 q := vn / math.Exp(-0.5*dn*dn)
219 testKn[0] = uint32((dn / q) * m1)
220 testKn[1] = 0
221 testWn[0] = float32(q / m1)
222 testWn[127] = float32(dn / m1)
223 testFn[0] = 1.0
224 testFn[127] = float32(math.Exp(-0.5 * dn * dn))
225 for i := 126; i >= 1; i-- {
226 dn = math.Sqrt(-2.0 * math.Log(vn/dn+math.Exp(-0.5*dn*dn)))
227 testKn[i+1] = uint32((dn / tn) * m1)
228 tn = dn
229 testFn[i] = float32(math.Exp(-0.5 * dn * dn))
230 testWn[i] = float32(dn / m1)
231 }
232 return
233 }
234
235 func initExp() (testKe []uint32, testWe, testFe []float32) {
236 const m2 = 1 << 32
237 var (
238 de float64 = re
239 te = de
240 ve float64 = 3.9496598225815571993e-3
241 )
242
243 testKe = make([]uint32, 256)
244 testWe = make([]float32, 256)
245 testFe = make([]float32, 256)
246
247 q := ve / math.Exp(-de)
248 testKe[0] = uint32((de / q) * m2)
249 testKe[1] = 0
250 testWe[0] = float32(q / m2)
251 testWe[255] = float32(de / m2)
252 testFe[0] = 1.0
253 testFe[255] = float32(math.Exp(-de))
254 for i := 254; i >= 1; i-- {
255 de = -math.Log(ve/de + math.Exp(-de))
256 testKe[i+1] = uint32((de / te) * m2)
257 te = de
258 testFe[i] = float32(math.Exp(-de))
259 testWe[i] = float32(de / m2)
260 }
261 return
262 }
263
264 // compareUint32Slices returns the first index where the two slices
265 // disagree, or <0 if the lengths are the same and all elements
266 // are identical.
267 func compareUint32Slices(s1, s2 []uint32) int {
268 if len(s1) != len(s2) {
269 if len(s1) > len(s2) {
270 return len(s2) + 1
271 }
272 return len(s1) + 1
273 }
274 for i := range s1 {
275 if s1[i] != s2[i] {
276 return i
277 }
278 }
279 return -1
280 }
281
282 // compareFloat32Slices returns the first index where the two slices
283 // disagree, or <0 if the lengths are the same and all elements
284 // are identical.
285 func compareFloat32Slices(s1, s2 []float32) int {
286 if len(s1) != len(s2) {
287 if len(s1) > len(s2) {
288 return len(s2) + 1
289 }
290 return len(s1) + 1
291 }
292 for i := range s1 {
293 if !nearEqual(float64(s1[i]), float64(s2[i]), 0, 1e-7) {
294 return i
295 }
296 }
297 return -1
298 }
299
300 func TestNormTables(t *testing.T) {
301 testKn, testWn, testFn := initNorm()
302 if i := compareUint32Slices(kn[0:], testKn); i >= 0 {
303 t.Errorf("kn disagrees at index %v; %v != %v", i, kn[i], testKn[i])
304 }
305 if i := compareFloat32Slices(wn[0:], testWn); i >= 0 {
306 t.Errorf("wn disagrees at index %v; %v != %v", i, wn[i], testWn[i])
307 }
308 if i := compareFloat32Slices(fn[0:], testFn); i >= 0 {
309 t.Errorf("fn disagrees at index %v; %v != %v", i, fn[i], testFn[i])
310 }
311 }
312
313 func TestExpTables(t *testing.T) {
314 testKe, testWe, testFe := initExp()
315 if i := compareUint32Slices(ke[0:], testKe); i >= 0 {
316 t.Errorf("ke disagrees at index %v; %v != %v", i, ke[i], testKe[i])
317 }
318 if i := compareFloat32Slices(we[0:], testWe); i >= 0 {
319 t.Errorf("we disagrees at index %v; %v != %v", i, we[i], testWe[i])
320 }
321 if i := compareFloat32Slices(fe[0:], testFe); i >= 0 {
322 t.Errorf("fe disagrees at index %v; %v != %v", i, fe[i], testFe[i])
323 }
324 }
325
326 func hasSlowFloatingPoint() bool {
327 switch runtime.GOARCH {
328 case "arm":
329 return os.Getenv("GOARM") == "5"
330 case "mips", "mipsle", "mips64", "mips64le":
331 // Be conservative and assume that all mips boards
332 // have emulated floating point.
333 // TODO: detect what it actually has.
334 return true
335 }
336 return false
337 }
338
339 func TestFloat32(t *testing.T) {
340 // For issue 6721, the problem came after 7533753 calls, so check 10e6.
341 num := int(10e6)
342 // But do the full amount only on builders (not locally).
343 // But ARM5 floating point emulation is slow (Issue 10749), so
344 // do less for that builder:
345 if testing.Short() && hasSlowFloatingPoint() { // TODO: (testenv.Builder() == "" || hasSlowFloatingPoint())
346 num /= 100 // 1.72 seconds instead of 172 seconds
347 }
348
349 r := New(NewSource(1))
350 for ct := 0; ct < num; ct++ {
351 f := r.Float32()
352 if f >= 1 {
353 t.Fatal("Float32() should be in range [0,1). ct:", ct, "f:", f)
354 }
355 }
356 }
357
358 func testReadUniformity(t *testing.T, n int, seed uint64) {
359 r := New(NewSource(seed))
360 buf := make([]byte, n)
361 nRead, err := r.Read(buf)
362 if err != nil {
363 t.Errorf("Read err %v", err)
364 }
365 if nRead != n {
366 t.Errorf("Read returned unexpected n; %d != %d", nRead, n)
367 }
368
369 // Expect a uniform distribution of byte values, which lie in [0, 255].
370 var (
371 mean = 255.0 / 2
372 stddev = 256.0 / math.Sqrt(12.0)
373 errorScale = stddev / math.Sqrt(float64(n))
374 )
375
376 expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.08 * errorScale}
377
378 // Cast bytes as floats to use the common distribution-validity checks.
379 samples := make([]float64, n)
380 for i, val := range buf {
381 samples[i] = float64(val)
382 }
383 // Make sure that the entire set matches the expected distribution.
384 checkSampleDistribution(t, samples, expected)
385 }
386
387 func TestReadUniformity(t *testing.T) {
388 testBufferSizes := []int{
389 2, 4, 7, 64, 1024, 1 << 16, 1 << 20,
390 }
391 for _, seed := range testSeeds {
392 for _, n := range testBufferSizes {
393 testReadUniformity(t, n, seed)
394 }
395 }
396 }
397
398 func TestReadEmpty(t *testing.T) {
399 r := New(NewSource(1))
400 buf := make([]byte, 0)
401 n, err := r.Read(buf)
402 if err != nil {
403 t.Errorf("Read err into empty buffer; %v", err)
404 }
405 if n != 0 {
406 t.Errorf("Read into empty buffer returned unexpected n of %d", n)
407 }
408 }
409
410 func TestReadByOneByte(t *testing.T) {
411 r := New(NewSource(1))
412 b1 := make([]byte, 100)
413 _, err := io.ReadFull(iotest.OneByteReader(r), b1)
414 if err != nil {
415 t.Errorf("read by one byte: %v", err)
416 }
417 r = New(NewSource(1))
418 b2 := make([]byte, 100)
419 _, err = r.Read(b2)
420 if err != nil {
421 t.Errorf("read: %v", err)
422 }
423 if !bytes.Equal(b1, b2) {
424 t.Errorf("read by one byte vs single read:\n%x\n%x", b1, b2)
425 }
426 }
427
428 func TestReadSeedReset(t *testing.T) {
429 r := New(NewSource(42))
430 b1 := make([]byte, 128)
431 _, err := r.Read(b1)
432 if err != nil {
433 t.Errorf("read: %v", err)
434 }
435 r.Seed(42)
436 b2 := make([]byte, 128)
437 _, err = r.Read(b2)
438 if err != nil {
439 t.Errorf("read: %v", err)
440 }
441 if !bytes.Equal(b1, b2) {
442 t.Errorf("mismatch after re-seed:\n%x\n%x", b1, b2)
443 }
444 }
445
446 func TestShuffleSmall(t *testing.T) {
447 // Check that Shuffle allows n=0 and n=1, but that swap is never called for them.
448 r := New(NewSource(1))
449 for n := 0; n <= 1; n++ {
450 r.Shuffle(n, func(i, j int) { t.Fatalf("swap called, n=%d i=%d j=%d", n, i, j) })
451 }
452 }
453
454 func TestPCGSourceRoundTrip(t *testing.T) {
455 var src PCGSource
456 src.Seed(uint64(time.Now().Unix()))
457
458 src.Uint64() // Step PRNG once to makes sure high and low are different.
459
460 buf, err := src.MarshalBinary()
461 if err != nil {
462 t.Errorf("unexpected error marshaling state: %v", err)
463 }
464
465 var dst PCGSource
466 // Get dst into a non-zero state.
467 dst.Seed(1)
468 for i := 0; i < 10; i++ {
469 dst.Uint64()
470 }
471
472 err = dst.UnmarshalBinary(buf)
473 if err != nil {
474 t.Errorf("unexpected error unmarshaling state: %v", err)
475 }
476
477 if dst != src {
478 t.Errorf("mismatch between generator states: got:%+v want:%+v", dst, src)
479 }
480 }
481
482 // Benchmarks
483
484 func BenchmarkSource(b *testing.B) {
485 rng := NewSource(0)
486 for n := b.N; n > 0; n-- {
487 rng.Uint64()
488 }
489 }
490
491 func BenchmarkInt63Threadsafe(b *testing.B) {
492 for n := b.N; n > 0; n-- {
493 Int63()
494 }
495 }
496
497 func BenchmarkInt63ThreadsafeParallel(b *testing.B) {
498 b.RunParallel(func(pb *testing.PB) {
499 for pb.Next() {
500 Int63()
501 }
502 })
503 }
504
505 func BenchmarkInt63Unthreadsafe(b *testing.B) {
506 r := New(NewSource(1))
507 for n := b.N; n > 0; n-- {
508 r.Int63()
509 }
510 }
511
512 func BenchmarkIntn1000(b *testing.B) {
513 r := New(NewSource(1))
514 for n := b.N; n > 0; n-- {
515 r.Intn(1000)
516 }
517 }
518
519 func BenchmarkInt63n1000(b *testing.B) {
520 r := New(NewSource(1))
521 for n := b.N; n > 0; n-- {
522 r.Int63n(1000)
523 }
524 }
525
526 func BenchmarkInt31n1000(b *testing.B) {
527 r := New(NewSource(1))
528 for n := b.N; n > 0; n-- {
529 r.Int31n(1000)
530 }
531 }
532
533 func BenchmarkFloat32(b *testing.B) {
534 r := New(NewSource(1))
535 for n := b.N; n > 0; n-- {
536 r.Float32()
537 }
538 }
539
540 func BenchmarkFloat64(b *testing.B) {
541 r := New(NewSource(1))
542 for n := b.N; n > 0; n-- {
543 r.Float64()
544 }
545 }
546
547 func BenchmarkPerm3(b *testing.B) {
548 r := New(NewSource(1))
549 for n := b.N; n > 0; n-- {
550 r.Perm(3)
551 }
552 }
553
554 func BenchmarkPerm30(b *testing.B) {
555 r := New(NewSource(1))
556 for n := b.N; n > 0; n-- {
557 r.Perm(30)
558 }
559 }
560
561 func BenchmarkPerm30ViaShuffle(b *testing.B) {
562 r := New(NewSource(1))
563 for n := b.N; n > 0; n-- {
564 p := make([]int, 30)
565 for i := range p {
566 p[i] = i
567 }
568 r.Shuffle(30, func(i, j int) { p[i], p[j] = p[j], p[i] })
569 }
570 }
571
572 // BenchmarkShuffleOverhead uses a minimal swap function
573 // to measure just the shuffling overhead.
574 func BenchmarkShuffleOverhead(b *testing.B) {
575 r := New(NewSource(1))
576 for n := b.N; n > 0; n-- {
577 r.Shuffle(52, func(i, j int) {
578 if i < 0 || i >= 52 || j < 0 || j >= 52 {
579 b.Fatalf("bad swap(%d, %d)", i, j)
580 }
581 })
582 }
583 }
584
585 func BenchmarkRead3(b *testing.B) {
586 r := New(NewSource(1))
587 buf := make([]byte, 3)
588 b.ResetTimer()
589 for n := b.N; n > 0; n-- {
590 r.Read(buf)
591 }
592 }
593
594 func BenchmarkRead64(b *testing.B) {
595 r := New(NewSource(1))
596 buf := make([]byte, 64)
597 b.ResetTimer()
598 for n := b.N; n > 0; n-- {
599 r.Read(buf)
600 }
601 }
602
603 func BenchmarkRead1000(b *testing.B) {
604 r := New(NewSource(1))
605 buf := make([]byte, 1000)
606 b.ResetTimer()
607 for n := b.N; n > 0; n-- {
608 r.Read(buf)
609 }
610 }