github.com/dara-project/godist@v0.0.0-20200823115410-e0c80c8f0c78/src/math/rand/rand.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 implements pseudo-random number generators.
     6  //
     7  // Random numbers are generated by a Source. Top-level functions, such as
     8  // Float64 and Int, use a default shared Source that produces a deterministic
     9  // sequence of values each time a program is run. Use the Seed function to
    10  // initialize the default Source if different behavior is required for each run.
    11  // The default Source is safe for concurrent use by multiple goroutines, but
    12  // Sources created by NewSource are not.
    13  //
    14  // For random numbers suitable for security-sensitive work, see the crypto/rand
    15  // package.
    16  package rand
    17  
    18  import "sync"
    19  import "runtime"
    20  
    21  // A Source represents a source of uniformly-distributed
    22  // pseudo-random int64 values in the range [0, 1<<63).
    23  type Source interface {
    24  	Int63() int64
    25  	Seed(seed int64)
    26  }
    27  
    28  // A Source64 is a Source that can also generate
    29  // uniformly-distributed pseudo-random uint64 values in
    30  // the range [0, 1<<64) directly.
    31  // If a Rand r's underlying Source s implements Source64,
    32  // then r.Uint64 returns the result of one call to s.Uint64
    33  // instead of making two calls to s.Int63.
    34  type Source64 interface {
    35  	Source
    36  	Uint64() uint64
    37  }
    38  
    39  // NewSource returns a new pseudo-random Source seeded with the given value.
    40  // Unlike the default Source used by top-level functions, this source is not
    41  // safe for concurrent use by multiple goroutines.
    42  func NewSource(seed int64) Source {
    43  	var rng rngSource
    44  	rng.Seed(seed)
    45  	return &rng
    46  }
    47  
    48  // A Rand is a source of random numbers.
    49  type Rand struct {
    50  	src Source
    51  	s64 Source64 // non-nil if src is source64
    52  
    53  	// readVal contains remainder of 63-bit integer used for bytes
    54  	// generation during most recent Read call.
    55  	// It is saved so next Read call can start where the previous
    56  	// one finished.
    57  	readVal int64
    58  	// readPos indicates the number of low-order bytes of readVal
    59  	// that are still valid.
    60  	readPos int8
    61  }
    62  
    63  // New returns a new Rand that uses random values from src
    64  // to generate other random values.
    65  func New(src Source) *Rand {
    66  	s64, _ := src.(Source64)
    67  	return &Rand{src: src, s64: s64}
    68  }
    69  
    70  // Seed uses the provided seed value to initialize the generator to a deterministic state.
    71  // Seed should not be called concurrently with any other Rand method.
    72  func (r *Rand) Seed(seed int64) {
    73  	//@DARA INJECT
    74      if runtime.DaraInitialised {
    75  	    seed = 0
    76      }
    77  	//@DARA /INJECT
    78  	if lk, ok := r.src.(*lockedSource); ok {
    79  		lk.seedPos(seed, &r.readPos)
    80  		return
    81  	}
    82  
    83  	r.src.Seed(seed)
    84  	r.readPos = 0
    85  }
    86  
    87  // Int63 returns a non-negative pseudo-random 63-bit integer as an int64.
    88  func (r *Rand) Int63() int64 { return r.src.Int63() }
    89  
    90  // Uint32 returns a pseudo-random 32-bit value as a uint32.
    91  func (r *Rand) Uint32() uint32 { return uint32(r.Int63() >> 31) }
    92  
    93  // Uint64 returns a pseudo-random 64-bit value as a uint64.
    94  func (r *Rand) Uint64() uint64 {
    95  	if r.s64 != nil {
    96  		return r.s64.Uint64()
    97  	}
    98  	return uint64(r.Int63())>>31 | uint64(r.Int63())<<32
    99  }
   100  
   101  // Int31 returns a non-negative pseudo-random 31-bit integer as an int32.
   102  func (r *Rand) Int31() int32 { return int32(r.Int63() >> 32) }
   103  
   104  // Int returns a non-negative pseudo-random int.
   105  func (r *Rand) Int() int {
   106  	u := uint(r.Int63())
   107  	return int(u << 1 >> 1) // clear sign bit if int == int32
   108  }
   109  
   110  // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n).
   111  // It panics if n <= 0.
   112  func (r *Rand) Int63n(n int64) int64 {
   113  	if n <= 0 {
   114  		panic("invalid argument to Int63n")
   115  	}
   116  	if n&(n-1) == 0 { // n is power of two, can mask
   117  		return r.Int63() & (n - 1)
   118  	}
   119  	max := int64((1 << 63) - 1 - (1<<63)%uint64(n))
   120  	v := r.Int63()
   121  	for v > max {
   122  		v = r.Int63()
   123  	}
   124  	return v % n
   125  }
   126  
   127  // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n).
   128  // It panics if n <= 0.
   129  func (r *Rand) Int31n(n int32) int32 {
   130  	if n <= 0 {
   131  		panic("invalid argument to Int31n")
   132  	}
   133  	if n&(n-1) == 0 { // n is power of two, can mask
   134  		return r.Int31() & (n - 1)
   135  	}
   136  	max := int32((1 << 31) - 1 - (1<<31)%uint32(n))
   137  	v := r.Int31()
   138  	for v > max {
   139  		v = r.Int31()
   140  	}
   141  	return v % n
   142  }
   143  
   144  // int31n returns, as an int32, a non-negative pseudo-random number in [0,n).
   145  // n must be > 0, but int31n does not check this; the caller must ensure it.
   146  // int31n exists because Int31n is inefficient, but Go 1 compatibility
   147  // requires that the stream of values produced by math/rand remain unchanged.
   148  // int31n can thus only be used internally, by newly introduced APIs.
   149  //
   150  // For implementation details, see:
   151  // https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction
   152  // https://lemire.me/blog/2016/06/30/fast-random-shuffling
   153  func (r *Rand) int31n(n int32) int32 {
   154  	v := r.Uint32()
   155  	prod := uint64(v) * uint64(n)
   156  	low := uint32(prod)
   157  	if low < uint32(n) {
   158  		thresh := uint32(-n) % uint32(n)
   159  		for low < thresh {
   160  			v = r.Uint32()
   161  			prod = uint64(v) * uint64(n)
   162  			low = uint32(prod)
   163  		}
   164  	}
   165  	return int32(prod >> 32)
   166  }
   167  
   168  // Intn returns, as an int, a non-negative pseudo-random number in [0,n).
   169  // It panics if n <= 0.
   170  func (r *Rand) Intn(n int) int {
   171  	if n <= 0 {
   172  		panic("invalid argument to Intn")
   173  	}
   174  	if n <= 1<<31-1 {
   175  		return int(r.Int31n(int32(n)))
   176  	}
   177  	return int(r.Int63n(int64(n)))
   178  }
   179  
   180  // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0).
   181  func (r *Rand) Float64() float64 {
   182  	// A clearer, simpler implementation would be:
   183  	//	return float64(r.Int63n(1<<53)) / (1<<53)
   184  	// However, Go 1 shipped with
   185  	//	return float64(r.Int63()) / (1 << 63)
   186  	// and we want to preserve that value stream.
   187  	//
   188  	// There is one bug in the value stream: r.Int63() may be so close
   189  	// to 1<<63 that the division rounds up to 1.0, and we've guaranteed
   190  	// that the result is always less than 1.0.
   191  	//
   192  	// We tried to fix this by mapping 1.0 back to 0.0, but since float64
   193  	// values near 0 are much denser than near 1, mapping 1 to 0 caused
   194  	// a theoretically significant overshoot in the probability of returning 0.
   195  	// Instead of that, if we round up to 1, just try again.
   196  	// Getting 1 only happens 1/2⁵³ of the time, so most clients
   197  	// will not observe it anyway.
   198  again:
   199  	f := float64(r.Int63()) / (1 << 63)
   200  	if f == 1 {
   201  		goto again // resample; this branch is taken O(never)
   202  	}
   203  	return f
   204  }
   205  
   206  // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0).
   207  func (r *Rand) Float32() float32 {
   208  	// Same rationale as in Float64: we want to preserve the Go 1 value
   209  	// stream except we want to fix it not to return 1.0
   210  	// This only happens 1/2²⁴ of the time (plus the 1/2⁵³ of the time in Float64).
   211  again:
   212  	f := float32(r.Float64())
   213  	if f == 1 {
   214  		goto again // resample; this branch is taken O(very rarely)
   215  	}
   216  	return f
   217  }
   218  
   219  // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n).
   220  func (r *Rand) Perm(n int) []int {
   221  	m := make([]int, n)
   222  	// In the following loop, the iteration when i=0 always swaps m[0] with m[0].
   223  	// A change to remove this useless iteration is to assign 1 to i in the init
   224  	// statement. But Perm also effects r. Making this change will affect
   225  	// the final state of r. So this change can't be made for compatibility
   226  	// reasons for Go 1.
   227  	for i := 0; i < n; i++ {
   228  		j := r.Intn(i + 1)
   229  		m[i] = m[j]
   230  		m[j] = i
   231  	}
   232  	return m
   233  }
   234  
   235  // Shuffle pseudo-randomizes the order of elements.
   236  // n is the number of elements. Shuffle panics if n < 0.
   237  // swap swaps the elements with indexes i and j.
   238  func (r *Rand) Shuffle(n int, swap func(i, j int)) {
   239  	if n < 0 {
   240  		panic("invalid argument to Shuffle")
   241  	}
   242  
   243  	// Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
   244  	// Shuffle really ought not be called with n that doesn't fit in 32 bits.
   245  	// Not only will it take a very long time, but with 2³¹! possible permutations,
   246  	// there's no way that any PRNG can have a big enough internal state to
   247  	// generate even a minuscule percentage of the possible permutations.
   248  	// Nevertheless, the right API signature accepts an int n, so handle it as best we can.
   249  	i := n - 1
   250  	for ; i > 1<<31-1-1; i-- {
   251  		j := int(r.Int63n(int64(i + 1)))
   252  		swap(i, j)
   253  	}
   254  	for ; i > 0; i-- {
   255  		j := int(r.int31n(int32(i + 1)))
   256  		swap(i, j)
   257  	}
   258  }
   259  
   260  // Read generates len(p) random bytes and writes them into p. It
   261  // always returns len(p) and a nil error.
   262  // Read should not be called concurrently with any other Rand method.
   263  func (r *Rand) Read(p []byte) (n int, err error) {
   264  	if lk, ok := r.src.(*lockedSource); ok {
   265  		return lk.read(p, &r.readVal, &r.readPos)
   266  	}
   267  	return read(p, r.Int63, &r.readVal, &r.readPos)
   268  }
   269  
   270  func read(p []byte, int63 func() int64, readVal *int64, readPos *int8) (n int, err error) {
   271  	pos := *readPos
   272  	val := *readVal
   273  	for n = 0; n < len(p); n++ {
   274  		if pos == 0 {
   275  			val = int63()
   276  			pos = 7
   277  		}
   278  		p[n] = byte(val)
   279  		val >>= 8
   280  		pos--
   281  	}
   282  	*readPos = pos
   283  	*readVal = val
   284  	return
   285  }
   286  
   287  /*
   288   * Top-level convenience functions
   289   */
   290  
   291  var globalRand = New(&lockedSource{src: NewSource(1).(Source64)})
   292  
   293  // Seed uses the provided seed value to initialize the default Source to a
   294  // deterministic state. If Seed is not called, the generator behaves as
   295  // if seeded by Seed(1). Seed values that have the same remainder when
   296  // divided by 2^31-1 generate the same pseudo-random sequence.
   297  // Seed, unlike the Rand.Seed method, is safe for concurrent use.
   298  func Seed(seed int64) { globalRand.Seed(seed) }
   299  
   300  // Int63 returns a non-negative pseudo-random 63-bit integer as an int64
   301  // from the default Source.
   302  func Int63() int64 { return globalRand.Int63() }
   303  
   304  // Uint32 returns a pseudo-random 32-bit value as a uint32
   305  // from the default Source.
   306  func Uint32() uint32 { return globalRand.Uint32() }
   307  
   308  // Uint64 returns a pseudo-random 64-bit value as a uint64
   309  // from the default Source.
   310  func Uint64() uint64 { return globalRand.Uint64() }
   311  
   312  // Int31 returns a non-negative pseudo-random 31-bit integer as an int32
   313  // from the default Source.
   314  func Int31() int32 { return globalRand.Int31() }
   315  
   316  // Int returns a non-negative pseudo-random int from the default Source.
   317  func Int() int { return globalRand.Int() }
   318  
   319  // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n)
   320  // from the default Source.
   321  // It panics if n <= 0.
   322  func Int63n(n int64) int64 { return globalRand.Int63n(n) }
   323  
   324  // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n)
   325  // from the default Source.
   326  // It panics if n <= 0.
   327  func Int31n(n int32) int32 { return globalRand.Int31n(n) }
   328  
   329  // Intn returns, as an int, a non-negative pseudo-random number in [0,n)
   330  // from the default Source.
   331  // It panics if n <= 0.
   332  func Intn(n int) int { return globalRand.Intn(n) }
   333  
   334  // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0)
   335  // from the default Source.
   336  func Float64() float64 { return globalRand.Float64() }
   337  
   338  // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0)
   339  // from the default Source.
   340  func Float32() float32 { return globalRand.Float32() }
   341  
   342  // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n)
   343  // from the default Source.
   344  func Perm(n int) []int { return globalRand.Perm(n) }
   345  
   346  // Shuffle pseudo-randomizes the order of elements using the default Source.
   347  // n is the number of elements. Shuffle panics if n < 0.
   348  // swap swaps the elements with indexes i and j.
   349  func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }
   350  
   351  // Read generates len(p) random bytes from the default Source and
   352  // writes them into p. It always returns len(p) and a nil error.
   353  // Read, unlike the Rand.Read method, is safe for concurrent use.
   354  func Read(p []byte) (n int, err error) { return globalRand.Read(p) }
   355  
   356  // NormFloat64 returns a normally distributed float64 in the range
   357  // [-math.MaxFloat64, +math.MaxFloat64] with
   358  // standard normal distribution (mean = 0, stddev = 1)
   359  // from the default Source.
   360  // To produce a different normal distribution, callers can
   361  // adjust the output using:
   362  //
   363  //  sample = NormFloat64() * desiredStdDev + desiredMean
   364  //
   365  func NormFloat64() float64 { return globalRand.NormFloat64() }
   366  
   367  // ExpFloat64 returns an exponentially distributed float64 in the range
   368  // (0, +math.MaxFloat64] with an exponential distribution whose rate parameter
   369  // (lambda) is 1 and whose mean is 1/lambda (1) from the default Source.
   370  // To produce a distribution with a different rate parameter,
   371  // callers can adjust the output using:
   372  //
   373  //  sample = ExpFloat64() / desiredRateParameter
   374  //
   375  func ExpFloat64() float64 { return globalRand.ExpFloat64() }
   376  
   377  type lockedSource struct {
   378  	lk  sync.Mutex
   379  	src Source64
   380  }
   381  
   382  func (r *lockedSource) Int63() (n int64) {
   383  	r.lk.Lock()
   384  	n = r.src.Int63()
   385  	r.lk.Unlock()
   386  	return
   387  }
   388  
   389  func (r *lockedSource) Uint64() (n uint64) {
   390  	r.lk.Lock()
   391  	n = r.src.Uint64()
   392  	r.lk.Unlock()
   393  	return
   394  }
   395  
   396  func (r *lockedSource) Seed(seed int64) {
   397  	r.lk.Lock()
   398  	r.src.Seed(seed)
   399  	r.lk.Unlock()
   400  }
   401  
   402  // seedPos implements Seed for a lockedSource without a race condition.
   403  func (r *lockedSource) seedPos(seed int64, readPos *int8) {
   404  	r.lk.Lock()
   405  	r.src.Seed(seed)
   406  	*readPos = 0
   407  	r.lk.Unlock()
   408  }
   409  
   410  // read implements Read for a lockedSource without a race condition.
   411  func (r *lockedSource) read(p []byte, readVal *int64, readPos *int8) (n int, err error) {
   412  	r.lk.Lock()
   413  	n, err = read(p, r.src.Int63, readVal, readPos)
   414  	r.lk.Unlock()
   415  	return
   416  }