github.com/gocuntian/go@v0.0.0-20160610041250-fee02d270bf8/src/math/rand/rand_test.go (about) 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 "errors" 9 "fmt" 10 "internal/testenv" 11 "math" 12 "os" 13 "runtime" 14 "testing" 15 ) 16 17 const ( 18 numTestSamples = 10000 19 ) 20 21 type statsResults struct { 22 mean float64 23 stddev float64 24 closeEnough float64 25 maxError float64 26 } 27 28 func max(a, b float64) float64 { 29 if a > b { 30 return a 31 } 32 return b 33 } 34 35 func nearEqual(a, b, closeEnough, maxError float64) bool { 36 absDiff := math.Abs(a - b) 37 if absDiff < closeEnough { // Necessary when one value is zero and one value is close to zero. 38 return true 39 } 40 return absDiff/max(math.Abs(a), math.Abs(b)) < maxError 41 } 42 43 var testSeeds = []int64{1, 1754801282, 1698661970, 1550503961} 44 45 // checkSimilarDistribution returns success if the mean and stddev of the 46 // two statsResults are similar. 47 func (this *statsResults) checkSimilarDistribution(expected *statsResults) error { 48 if !nearEqual(this.mean, expected.mean, expected.closeEnough, expected.maxError) { 49 s := fmt.Sprintf("mean %v != %v (allowed error %v, %v)", this.mean, expected.mean, expected.closeEnough, expected.maxError) 50 fmt.Println(s) 51 return errors.New(s) 52 } 53 if !nearEqual(this.stddev, expected.stddev, 0, expected.maxError) { 54 s := fmt.Sprintf("stddev %v != %v (allowed error %v, %v)", this.stddev, expected.stddev, expected.closeEnough, expected.maxError) 55 fmt.Println(s) 56 return errors.New(s) 57 } 58 return nil 59 } 60 61 func getStatsResults(samples []float64) *statsResults { 62 res := new(statsResults) 63 var sum, squaresum float64 64 for _, s := range samples { 65 sum += s 66 squaresum += s * s 67 } 68 res.mean = sum / float64(len(samples)) 69 res.stddev = math.Sqrt(squaresum/float64(len(samples)) - res.mean*res.mean) 70 return res 71 } 72 73 func checkSampleDistribution(t *testing.T, samples []float64, expected *statsResults) { 74 actual := getStatsResults(samples) 75 err := actual.checkSimilarDistribution(expected) 76 if err != nil { 77 t.Errorf(err.Error()) 78 } 79 } 80 81 func checkSampleSliceDistributions(t *testing.T, samples []float64, nslices int, expected *statsResults) { 82 chunk := len(samples) / nslices 83 for i := 0; i < nslices; i++ { 84 low := i * chunk 85 var high int 86 if i == nslices-1 { 87 high = len(samples) - 1 88 } else { 89 high = (i + 1) * chunk 90 } 91 checkSampleDistribution(t, samples[low:high], expected) 92 } 93 } 94 95 // 96 // Normal distribution tests 97 // 98 99 func generateNormalSamples(nsamples int, mean, stddev float64, seed int64) []float64 { 100 r := New(NewSource(seed)) 101 samples := make([]float64, nsamples) 102 for i := range samples { 103 samples[i] = r.NormFloat64()*stddev + mean 104 } 105 return samples 106 } 107 108 func testNormalDistribution(t *testing.T, nsamples int, mean, stddev float64, seed int64) { 109 //fmt.Printf("testing nsamples=%v mean=%v stddev=%v seed=%v\n", nsamples, mean, stddev, seed); 110 111 samples := generateNormalSamples(nsamples, mean, stddev, seed) 112 errorScale := max(1.0, stddev) // Error scales with stddev 113 expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.08 * errorScale} 114 115 // Make sure that the entire set matches the expected distribution. 116 checkSampleDistribution(t, samples, expected) 117 118 // Make sure that each half of the set matches the expected distribution. 119 checkSampleSliceDistributions(t, samples, 2, expected) 120 121 // Make sure that each 7th of the set matches the expected distribution. 122 checkSampleSliceDistributions(t, samples, 7, expected) 123 } 124 125 // Actual tests 126 127 func TestStandardNormalValues(t *testing.T) { 128 for _, seed := range testSeeds { 129 testNormalDistribution(t, numTestSamples, 0, 1, seed) 130 } 131 } 132 133 func TestNonStandardNormalValues(t *testing.T) { 134 sdmax := 1000.0 135 mmax := 1000.0 136 if testing.Short() { 137 sdmax = 5 138 mmax = 5 139 } 140 for sd := 0.5; sd < sdmax; sd *= 2 { 141 for m := 0.5; m < mmax; m *= 2 { 142 for _, seed := range testSeeds { 143 testNormalDistribution(t, numTestSamples, m, sd, seed) 144 if testing.Short() { 145 break 146 } 147 } 148 } 149 } 150 } 151 152 // 153 // Exponential distribution tests 154 // 155 156 func generateExponentialSamples(nsamples int, rate float64, seed int64) []float64 { 157 r := New(NewSource(seed)) 158 samples := make([]float64, nsamples) 159 for i := range samples { 160 samples[i] = r.ExpFloat64() / rate 161 } 162 return samples 163 } 164 165 func testExponentialDistribution(t *testing.T, nsamples int, rate float64, seed int64) { 166 //fmt.Printf("testing nsamples=%v rate=%v seed=%v\n", nsamples, rate, seed); 167 168 mean := 1 / rate 169 stddev := mean 170 171 samples := generateExponentialSamples(nsamples, rate, seed) 172 errorScale := max(1.0, 1/rate) // Error scales with the inverse of the rate 173 expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.20 * errorScale} 174 175 // Make sure that the entire set matches the expected distribution. 176 checkSampleDistribution(t, samples, expected) 177 178 // Make sure that each half of the set matches the expected distribution. 179 checkSampleSliceDistributions(t, samples, 2, expected) 180 181 // Make sure that each 7th of the set matches the expected distribution. 182 checkSampleSliceDistributions(t, samples, 7, expected) 183 } 184 185 // Actual tests 186 187 func TestStandardExponentialValues(t *testing.T) { 188 for _, seed := range testSeeds { 189 testExponentialDistribution(t, numTestSamples, 1, seed) 190 } 191 } 192 193 func TestNonStandardExponentialValues(t *testing.T) { 194 for rate := 0.05; rate < 10; rate *= 2 { 195 for _, seed := range testSeeds { 196 testExponentialDistribution(t, numTestSamples, rate, seed) 197 if testing.Short() { 198 break 199 } 200 } 201 } 202 } 203 204 // 205 // Table generation tests 206 // 207 208 func initNorm() (testKn []uint32, testWn, testFn []float32) { 209 const m1 = 1 << 31 210 var ( 211 dn float64 = rn 212 tn = dn 213 vn float64 = 9.91256303526217e-3 214 ) 215 216 testKn = make([]uint32, 128) 217 testWn = make([]float32, 128) 218 testFn = make([]float32, 128) 219 220 q := vn / math.Exp(-0.5*dn*dn) 221 testKn[0] = uint32((dn / q) * m1) 222 testKn[1] = 0 223 testWn[0] = float32(q / m1) 224 testWn[127] = float32(dn / m1) 225 testFn[0] = 1.0 226 testFn[127] = float32(math.Exp(-0.5 * dn * dn)) 227 for i := 126; i >= 1; i-- { 228 dn = math.Sqrt(-2.0 * math.Log(vn/dn+math.Exp(-0.5*dn*dn))) 229 testKn[i+1] = uint32((dn / tn) * m1) 230 tn = dn 231 testFn[i] = float32(math.Exp(-0.5 * dn * dn)) 232 testWn[i] = float32(dn / m1) 233 } 234 return 235 } 236 237 func initExp() (testKe []uint32, testWe, testFe []float32) { 238 const m2 = 1 << 32 239 var ( 240 de float64 = re 241 te = de 242 ve float64 = 3.9496598225815571993e-3 243 ) 244 245 testKe = make([]uint32, 256) 246 testWe = make([]float32, 256) 247 testFe = make([]float32, 256) 248 249 q := ve / math.Exp(-de) 250 testKe[0] = uint32((de / q) * m2) 251 testKe[1] = 0 252 testWe[0] = float32(q / m2) 253 testWe[255] = float32(de / m2) 254 testFe[0] = 1.0 255 testFe[255] = float32(math.Exp(-de)) 256 for i := 254; i >= 1; i-- { 257 de = -math.Log(ve/de + math.Exp(-de)) 258 testKe[i+1] = uint32((de / te) * m2) 259 te = de 260 testFe[i] = float32(math.Exp(-de)) 261 testWe[i] = float32(de / m2) 262 } 263 return 264 } 265 266 // compareUint32Slices returns the first index where the two slices 267 // disagree, or <0 if the lengths are the same and all elements 268 // are identical. 269 func compareUint32Slices(s1, s2 []uint32) int { 270 if len(s1) != len(s2) { 271 if len(s1) > len(s2) { 272 return len(s2) + 1 273 } 274 return len(s1) + 1 275 } 276 for i := range s1 { 277 if s1[i] != s2[i] { 278 return i 279 } 280 } 281 return -1 282 } 283 284 // compareFloat32Slices returns the first index where the two slices 285 // disagree, or <0 if the lengths are the same and all elements 286 // are identical. 287 func compareFloat32Slices(s1, s2 []float32) int { 288 if len(s1) != len(s2) { 289 if len(s1) > len(s2) { 290 return len(s2) + 1 291 } 292 return len(s1) + 1 293 } 294 for i := range s1 { 295 if !nearEqual(float64(s1[i]), float64(s2[i]), 0, 1e-7) { 296 return i 297 } 298 } 299 return -1 300 } 301 302 func TestNormTables(t *testing.T) { 303 testKn, testWn, testFn := initNorm() 304 if i := compareUint32Slices(kn[0:], testKn); i >= 0 { 305 t.Errorf("kn disagrees at index %v; %v != %v", i, kn[i], testKn[i]) 306 } 307 if i := compareFloat32Slices(wn[0:], testWn); i >= 0 { 308 t.Errorf("wn disagrees at index %v; %v != %v", i, wn[i], testWn[i]) 309 } 310 if i := compareFloat32Slices(fn[0:], testFn); i >= 0 { 311 t.Errorf("fn disagrees at index %v; %v != %v", i, fn[i], testFn[i]) 312 } 313 } 314 315 func TestExpTables(t *testing.T) { 316 testKe, testWe, testFe := initExp() 317 if i := compareUint32Slices(ke[0:], testKe); i >= 0 { 318 t.Errorf("ke disagrees at index %v; %v != %v", i, ke[i], testKe[i]) 319 } 320 if i := compareFloat32Slices(we[0:], testWe); i >= 0 { 321 t.Errorf("we disagrees at index %v; %v != %v", i, we[i], testWe[i]) 322 } 323 if i := compareFloat32Slices(fe[0:], testFe); i >= 0 { 324 t.Errorf("fe disagrees at index %v; %v != %v", i, fe[i], testFe[i]) 325 } 326 } 327 328 func TestFloat32(t *testing.T) { 329 // For issue 6721, the problem came after 7533753 calls, so check 10e6. 330 num := int(10e6) 331 // But do the full amount only on builders (not locally). 332 // But ARM5 floating point emulation is slow (Issue 10749), so 333 // do less for that builder: 334 if testing.Short() && (testenv.Builder() == "" || runtime.GOARCH == "arm" && os.Getenv("GOARM") == "5") { 335 num /= 100 // 1.72 seconds instead of 172 seconds 336 } 337 338 r := New(NewSource(1)) 339 for ct := 0; ct < num; ct++ { 340 f := r.Float32() 341 if f >= 1 { 342 t.Fatal("Float32() should be in range [0,1). ct:", ct, "f:", f) 343 } 344 } 345 } 346 347 func testReadUniformity(t *testing.T, n int, seed int64) { 348 r := New(NewSource(seed)) 349 buf := make([]byte, n) 350 nRead, err := r.Read(buf) 351 if err != nil { 352 t.Errorf("Read err %v", err) 353 } 354 if nRead != n { 355 t.Errorf("Read returned unexpected n; %d != %d", nRead, n) 356 } 357 358 // Expect a uniform distribution of byte values, which lie in [0, 255]. 359 var ( 360 mean = 255.0 / 2 361 stddev = math.Sqrt(255.0 * 255.0 / 12.0) 362 errorScale = stddev / math.Sqrt(float64(n)) 363 ) 364 365 expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.08 * errorScale} 366 367 // Cast bytes as floats to use the common distribution-validity checks. 368 samples := make([]float64, n) 369 for i, val := range buf { 370 samples[i] = float64(val) 371 } 372 // Make sure that the entire set matches the expected distribution. 373 checkSampleDistribution(t, samples, expected) 374 } 375 376 func TestRead(t *testing.T) { 377 testBufferSizes := []int{ 378 2, 4, 7, 64, 1024, 1 << 16, 1 << 20, 379 } 380 for _, seed := range testSeeds { 381 for _, n := range testBufferSizes { 382 testReadUniformity(t, n, seed) 383 } 384 } 385 } 386 387 func TestReadEmpty(t *testing.T) { 388 r := New(NewSource(1)) 389 buf := make([]byte, 0) 390 n, err := r.Read(buf) 391 if err != nil { 392 t.Errorf("Read err into empty buffer; %v", err) 393 } 394 if n != 0 { 395 t.Errorf("Read into empty buffer returned unexpected n of %d", n) 396 } 397 398 } 399 400 // Benchmarks 401 402 func BenchmarkInt63Threadsafe(b *testing.B) { 403 for n := b.N; n > 0; n-- { 404 Int63() 405 } 406 } 407 408 func BenchmarkInt63Unthreadsafe(b *testing.B) { 409 r := New(NewSource(1)) 410 for n := b.N; n > 0; n-- { 411 r.Int63() 412 } 413 } 414 415 func BenchmarkIntn1000(b *testing.B) { 416 r := New(NewSource(1)) 417 for n := b.N; n > 0; n-- { 418 r.Intn(1000) 419 } 420 } 421 422 func BenchmarkInt63n1000(b *testing.B) { 423 r := New(NewSource(1)) 424 for n := b.N; n > 0; n-- { 425 r.Int63n(1000) 426 } 427 } 428 429 func BenchmarkInt31n1000(b *testing.B) { 430 r := New(NewSource(1)) 431 for n := b.N; n > 0; n-- { 432 r.Int31n(1000) 433 } 434 } 435 436 func BenchmarkFloat32(b *testing.B) { 437 r := New(NewSource(1)) 438 for n := b.N; n > 0; n-- { 439 r.Float32() 440 } 441 } 442 443 func BenchmarkFloat64(b *testing.B) { 444 r := New(NewSource(1)) 445 for n := b.N; n > 0; n-- { 446 r.Float64() 447 } 448 } 449 450 func BenchmarkPerm3(b *testing.B) { 451 r := New(NewSource(1)) 452 for n := b.N; n > 0; n-- { 453 r.Perm(3) 454 } 455 } 456 457 func BenchmarkPerm30(b *testing.B) { 458 r := New(NewSource(1)) 459 for n := b.N; n > 0; n-- { 460 r.Perm(30) 461 } 462 } 463 464 func BenchmarkRead3(b *testing.B) { 465 r := New(NewSource(1)) 466 buf := make([]byte, 3) 467 b.ResetTimer() 468 for n := b.N; n > 0; n-- { 469 r.Read(buf) 470 } 471 } 472 473 func BenchmarkRead64(b *testing.B) { 474 r := New(NewSource(1)) 475 buf := make([]byte, 64) 476 b.ResetTimer() 477 for n := b.N; n > 0; n-- { 478 r.Read(buf) 479 } 480 } 481 482 func BenchmarkRead1000(b *testing.B) { 483 r := New(NewSource(1)) 484 buf := make([]byte, 1000) 485 b.ResetTimer() 486 for n := b.N; n > 0; n-- { 487 r.Read(buf) 488 } 489 }