Home | History | Annotate | Download | only in rand
      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 	// In the following loop, the iteration when i=0 always swaps m[0] with m[0].
    217 	// A change to remove this useless iteration is to assign 1 to i in the init
    218 	// statement. But Perm also effects r. Making this change will affect
    219 	// the final state of r. So this change can't be made for compatibility
    220 	// reasons for Go 1.
    221 	for i := 0; i < n; i++ {
    222 		j := r.Intn(i + 1)
    223 		m[i] = m[j]
    224 		m[j] = i
    225 	}
    226 	return m
    227 }
    228 
    229 // Shuffle pseudo-randomizes the order of elements.
    230 // n is the number of elements. Shuffle panics if n < 0.
    231 // swap swaps the elements with indexes i and j.
    232 func (r *Rand) Shuffle(n int, swap func(i, j int)) {
    233 	if n < 0 {
    234 		panic("invalid argument to Shuffle")
    235 	}
    236 
    237 	// Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
    238 	// Shuffle really ought not be called with n that doesn't fit in 32 bits.
    239 	// Not only will it take a very long time, but with 2! possible permutations,
    240 	// there's no way that any PRNG can have a big enough internal state to
    241 	// generate even a minuscule percentage of the possible permutations.
    242 	// Nevertheless, the right API signature accepts an int n, so handle it as best we can.
    243 	i := n - 1
    244 	for ; i > 1<<31-1-1; i-- {
    245 		j := int(r.Int63n(int64(i + 1)))
    246 		swap(i, j)
    247 	}
    248 	for ; i > 0; i-- {
    249 		j := int(r.int31n(int32(i + 1)))
    250 		swap(i, j)
    251 	}
    252 }
    253 
    254 // Read generates len(p) random bytes and writes them into p. It
    255 // always returns len(p) and a nil error.
    256 // Read should not be called concurrently with any other Rand method.
    257 func (r *Rand) Read(p []byte) (n int, err error) {
    258 	if lk, ok := r.src.(*lockedSource); ok {
    259 		return lk.read(p, &r.readVal, &r.readPos)
    260 	}
    261 	return read(p, r.Int63, &r.readVal, &r.readPos)
    262 }
    263 
    264 func read(p []byte, int63 func() int64, readVal *int64, readPos *int8) (n int, err error) {
    265 	pos := *readPos
    266 	val := *readVal
    267 	for n = 0; n < len(p); n++ {
    268 		if pos == 0 {
    269 			val = int63()
    270 			pos = 7
    271 		}
    272 		p[n] = byte(val)
    273 		val >>= 8
    274 		pos--
    275 	}
    276 	*readPos = pos
    277 	*readVal = val
    278 	return
    279 }
    280 
    281 /*
    282  * Top-level convenience functions
    283  */
    284 
    285 var globalRand = New(&lockedSource{src: NewSource(1).(Source64)})
    286 
    287 // Seed uses the provided seed value to initialize the default Source to a
    288 // deterministic state. If Seed is not called, the generator behaves as
    289 // if seeded by Seed(1). Seed values that have the same remainder when
    290 // divided by 2^31-1 generate the same pseudo-random sequence.
    291 // Seed, unlike the Rand.Seed method, is safe for concurrent use.
    292 func Seed(seed int64) { globalRand.Seed(seed) }
    293 
    294 // Int63 returns a non-negative pseudo-random 63-bit integer as an int64
    295 // from the default Source.
    296 func Int63() int64 { return globalRand.Int63() }
    297 
    298 // Uint32 returns a pseudo-random 32-bit value as a uint32
    299 // from the default Source.
    300 func Uint32() uint32 { return globalRand.Uint32() }
    301 
    302 // Uint64 returns a pseudo-random 64-bit value as a uint64
    303 // from the default Source.
    304 func Uint64() uint64 { return globalRand.Uint64() }
    305 
    306 // Int31 returns a non-negative pseudo-random 31-bit integer as an int32
    307 // from the default Source.
    308 func Int31() int32 { return globalRand.Int31() }
    309 
    310 // Int returns a non-negative pseudo-random int from the default Source.
    311 func Int() int { return globalRand.Int() }
    312 
    313 // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n)
    314 // from the default Source.
    315 // It panics if n <= 0.
    316 func Int63n(n int64) int64 { return globalRand.Int63n(n) }
    317 
    318 // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n)
    319 // from the default Source.
    320 // It panics if n <= 0.
    321 func Int31n(n int32) int32 { return globalRand.Int31n(n) }
    322 
    323 // Intn returns, as an int, a non-negative pseudo-random number in [0,n)
    324 // from the default Source.
    325 // It panics if n <= 0.
    326 func Intn(n int) int { return globalRand.Intn(n) }
    327 
    328 // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0)
    329 // from the default Source.
    330 func Float64() float64 { return globalRand.Float64() }
    331 
    332 // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0)
    333 // from the default Source.
    334 func Float32() float32 { return globalRand.Float32() }
    335 
    336 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n)
    337 // from the default Source.
    338 func Perm(n int) []int { return globalRand.Perm(n) }
    339 
    340 // Shuffle pseudo-randomizes the order of elements using the default Source.
    341 // n is the number of elements. Shuffle panics if n < 0.
    342 // swap swaps the elements with indexes i and j.
    343 func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }
    344 
    345 // Read generates len(p) random bytes from the default Source and
    346 // writes them into p. It always returns len(p) and a nil error.
    347 // Read, unlike the Rand.Read method, is safe for concurrent use.
    348 func Read(p []byte) (n int, err error) { return globalRand.Read(p) }
    349 
    350 // NormFloat64 returns a normally distributed float64 in the range
    351 // [-math.MaxFloat64, +math.MaxFloat64] with
    352 // standard normal distribution (mean = 0, stddev = 1)
    353 // from the default Source.
    354 // To produce a different normal distribution, callers can
    355 // adjust the output using:
    356 //
    357 //  sample = NormFloat64() * desiredStdDev + desiredMean
    358 //
    359 func NormFloat64() float64 { return globalRand.NormFloat64() }
    360 
    361 // ExpFloat64 returns an exponentially distributed float64 in the range
    362 // (0, +math.MaxFloat64] with an exponential distribution whose rate parameter
    363 // (lambda) is 1 and whose mean is 1/lambda (1) from the default Source.
    364 // To produce a distribution with a different rate parameter,
    365 // callers can adjust the output using:
    366 //
    367 //  sample = ExpFloat64() / desiredRateParameter
    368 //
    369 func ExpFloat64() float64 { return globalRand.ExpFloat64() }
    370 
    371 type lockedSource struct {
    372 	lk  sync.Mutex
    373 	src Source64
    374 }
    375 
    376 func (r *lockedSource) Int63() (n int64) {
    377 	r.lk.Lock()
    378 	n = r.src.Int63()
    379 	r.lk.Unlock()
    380 	return
    381 }
    382 
    383 func (r *lockedSource) Uint64() (n uint64) {
    384 	r.lk.Lock()
    385 	n = r.src.Uint64()
    386 	r.lk.Unlock()
    387 	return
    388 }
    389 
    390 func (r *lockedSource) Seed(seed int64) {
    391 	r.lk.Lock()
    392 	r.src.Seed(seed)
    393 	r.lk.Unlock()
    394 }
    395 
    396 // seedPos implements Seed for a lockedSource without a race condition.
    397 func (r *lockedSource) seedPos(seed int64, readPos *int8) {
    398 	r.lk.Lock()
    399 	r.src.Seed(seed)
    400 	*readPos = 0
    401 	r.lk.Unlock()
    402 }
    403 
    404 // read implements Read for a lockedSource without a race condition.
    405 func (r *lockedSource) read(p []byte, readVal *int64, readPos *int8) (n int, err error) {
    406 	r.lk.Lock()
    407 	n, err = read(p, r.src.Int63, readVal, readPos)
    408 	r.lk.Unlock()
    409 	return
    410 }
    411