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