gonum.org/v1/gonum@v0.14.0/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  	"golang.org/x/exp/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 golang.org/x/exp/rand.Source.
    26  type Source = rand.Source
    27  
    28  // Rand corresponds to golang.org/x/exp/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 uint64)
    43  	Shuffle(n int, swap func(i, j int))
    44  	Uint32() uint32
    45  	Uint64() uint64
    46  	Uint64n(n uint64) uint64
    47  }
    48  
    49  // New returns a new random number generator using the global flags.
    50  func New(tb TB) Rand {
    51  	seed := *seedFlag
    52  	if seed == 0 {
    53  		seed = rand.Uint64()
    54  	}
    55  
    56  	// Don't log the default case.
    57  	if seed == 1 && *extremeFlag == 0 && *nanFlag == 0 {
    58  		base := rand.New(rand.NewSource(seed))
    59  		return base
    60  	}
    61  
    62  	tb.Logf("seed=%d, prob=%.2f, nan=%.2f", seed, *extremeFlag, *nanFlag)
    63  
    64  	base := rand.New(rand.NewSource(seed))
    65  	if *extremeFlag <= 0 && *nanFlag <= 0 {
    66  		return base
    67  	}
    68  
    69  	return newExtreme(*extremeFlag, *nanFlag, base)
    70  }
    71  
    72  // NewSource returns a new source for random numbers.
    73  func NewSource(tb TB) Source {
    74  	seed := *seedFlag
    75  	if seed == 0 {
    76  		seed = rand.Uint64()
    77  	}
    78  
    79  	// Don't log the default case.
    80  	if seed == 1 {
    81  		return rand.NewSource(seed)
    82  	}
    83  
    84  	tb.Logf("seed %d", seed)
    85  	return rand.NewSource(seed)
    86  }