github.com/gopherd/gonum@v0.0.4/internal/testrand/rand.go (about) 1 // Copyright ©2020 The Gonum 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 testrand provides random generation and flags for testing. 6 package testrand 7 8 import ( 9 "flag" 10 11 "math/rand" 12 ) 13 14 var ( 15 seedFlag = flag.Uint64("testrand.seed", 1, "random seed for tests (0=randomize)") 16 extremeFlag = flag.Float64("testrand.extreme", 0, "probability of returning extreme values") 17 nanFlag = flag.Float64("testrand.nan", 0, "probability of returning nan") 18 ) 19 20 // TB is an interface that corresponds to a subset of *testing.T and *testing.B. 21 type TB interface { 22 Logf(format string, args ...interface{}) 23 } 24 25 // Source corresponds to the interface in math/rand.Source. 26 type Source = rand.Source 27 28 // Rand corresponds to math/rand.Rand. 29 type Rand interface { 30 ExpFloat64() float64 31 Float32() float32 32 Float64() float64 33 Int() int 34 Int31() int32 35 Int31n(n int32) int32 36 Int63() int64 37 Int63n(n int64) int64 38 Intn(n int) int 39 NormFloat64() float64 40 Perm(n int) []int 41 Read(p []byte) (n int, err error) 42 Seed(seed int64) 43 Shuffle(n int, swap func(i, j int)) 44 Uint32() uint32 45 Uint64() uint64 46 } 47 48 // New returns a new random number generator using the global flags. 49 func New(tb TB) Rand { 50 seed := *seedFlag 51 if seed == 0 { 52 seed = rand.Uint64() 53 } 54 55 // Don't log the default case. 56 if seed == 1 && *extremeFlag == 0 && *nanFlag == 0 { 57 base := rand.New(rand.NewSource(int64(seed))) 58 return base 59 } 60 61 tb.Logf("seed=%d, prob=%.2f, nan=%.2f", seed, *extremeFlag, *nanFlag) 62 63 base := rand.New(rand.NewSource(int64(seed))) 64 if *extremeFlag <= 0 && *nanFlag <= 0 { 65 return base 66 } 67 68 return newExtreme(*extremeFlag, *nanFlag, base) 69 } 70 71 // NewSource returns a new source for random numbers. 72 func NewSource(tb TB) Source { 73 seed := *seedFlag 74 if seed == 0 { 75 seed = rand.Uint64() 76 } 77 78 // Don't log the default case. 79 if seed == 1 { 80 return rand.NewSource(int64(seed)) 81 } 82 83 tb.Logf("seed %d", seed) 84 return rand.NewSource(int64(seed)) 85 }