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.
5 // Package rand implements pseudo-random number generators unsuitable for
6 // security-sensitive work.
8 // Random numbers are generated by a Source. Top-level functions, such as
9 // Float64 and Int, use a default shared Source that produces a deterministic
10 // sequence of values each time a program is run. Use the Seed function to
11 // initialize the default Source if different behavior is required for each run.
12 // The default Source is safe for concurrent use by multiple goroutines, but
13 // Sources created by NewSource are not.
15 // This package's outputs might be easily predictable regardless of how it's
16 // seeded. For random numbers suitable for security-sensitive work, see the
17 // crypto/rand package.
22 // A Source represents a source of uniformly-distributed
23 // pseudo-random int64 values in the range [0, 1<<63).
24 type Source
interface {
29 // A Source64 is a Source that can also generate
30 // uniformly-distributed pseudo-random uint64 values in
31 // the range [0, 1<<64) directly.
32 // If a Rand r's underlying Source s implements Source64,
33 // then r.Uint64 returns the result of one call to s.Uint64
34 // instead of making two calls to s.Int63.
35 type Source64
interface {
40 // NewSource returns a new pseudo-random Source seeded with the given value.
41 // Unlike the default Source used by top-level functions, this source is not
42 // safe for concurrent use by multiple goroutines.
43 func NewSource(seed
int64) Source
{
49 // A Rand is a source of random numbers.
52 s64 Source64
// non-nil if src is source64
54 // readVal contains remainder of 63-bit integer used for bytes
55 // generation during most recent Read call.
56 // It is saved so next Read call can start where the previous
59 // readPos indicates the number of low-order bytes of readVal
60 // that are still valid.
64 // New returns a new Rand that uses random values from src
65 // to generate other random values.
66 func New(src Source
) *Rand
{
67 s64
, _
:= src
.(Source64
)
68 return &Rand
{src
: src
, s64
: s64
}
71 // Seed uses the provided seed value to initialize the generator to a deterministic state.
72 // Seed should not be called concurrently with any other Rand method.
73 func (r
*Rand
) Seed(seed
int64) {
74 if lk
, ok
:= r
.src
.(*lockedSource
); ok
{
75 lk
.seedPos(seed
, &r
.readPos
)
83 // Int63 returns a non-negative pseudo-random 63-bit integer as an int64.
84 func (r
*Rand
) Int63() int64 { return r
.src
.Int63() }
86 // Uint32 returns a pseudo-random 32-bit value as a uint32.
87 func (r
*Rand
) Uint32() uint32 { return uint32(r
.Int63() >> 31) }
89 // Uint64 returns a pseudo-random 64-bit value as a uint64.
90 func (r
*Rand
) Uint64() uint64 {
94 return uint64(r
.Int63())>>31 |
uint64(r
.Int63())<<32
97 // Int31 returns a non-negative pseudo-random 31-bit integer as an int32.
98 func (r
*Rand
) Int31() int32 { return int32(r
.Int63() >> 32) }
100 // Int returns a non-negative pseudo-random int.
101 func (r
*Rand
) Int() int {
103 return int(u
<< 1 >> 1) // clear sign bit if int == int32
106 // Int63n returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n).
107 // It panics if n <= 0.
108 func (r
*Rand
) Int63n(n
int64) int64 {
110 panic("invalid argument to Int63n")
112 if n
&(n
-1) == 0 { // n is power of two, can mask
113 return r
.Int63() & (n
- 1)
115 max
:= int64((1 << 63) - 1 - (1<<63)%uint
64(n
))
123 // Int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n).
124 // It panics if n <= 0.
125 func (r
*Rand
) Int31n(n
int32) int32 {
127 panic("invalid argument to Int31n")
129 if n
&(n
-1) == 0 { // n is power of two, can mask
130 return r
.Int31() & (n
- 1)
132 max
:= int32((1 << 31) - 1 - (1<<31)%uint
32(n
))
140 // int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n).
141 // n must be > 0, but int31n does not check this; the caller must ensure it.
142 // int31n exists because Int31n is inefficient, but Go 1 compatibility
143 // requires that the stream of values produced by math/rand remain unchanged.
144 // int31n can thus only be used internally, by newly introduced APIs.
146 // For implementation details, see:
147 // https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction
148 // https://lemire.me/blog/2016/06/30/fast-random-shuffling
149 func (r
*Rand
) int31n(n
int32) int32 {
151 prod
:= uint64(v
) * uint64(n
)
154 thresh
:= uint32(-n
) % uint32(n
)
157 prod
= uint64(v
) * uint64(n
)
161 return int32(prod
>> 32)
164 // Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n).
165 // It panics if n <= 0.
166 func (r
*Rand
) Intn(n
int) int {
168 panic("invalid argument to Intn")
171 return int(r
.Int31n(int32(n
)))
173 return int(r
.Int63n(int64(n
)))
176 // Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0).
177 func (r
*Rand
) Float64() float64 {
178 // A clearer, simpler implementation would be:
179 // return float64(r.Int63n(1<<53)) / (1<<53)
180 // However, Go 1 shipped with
181 // return float64(r.Int63()) / (1 << 63)
182 // and we want to preserve that value stream.
184 // There is one bug in the value stream: r.Int63() may be so close
185 // to 1<<63 that the division rounds up to 1.0, and we've guaranteed
186 // that the result is always less than 1.0.
188 // We tried to fix this by mapping 1.0 back to 0.0, but since float64
189 // values near 0 are much denser than near 1, mapping 1 to 0 caused
190 // a theoretically significant overshoot in the probability of returning 0.
191 // Instead of that, if we round up to 1, just try again.
192 // Getting 1 only happens 1/2⁵³ of the time, so most clients
193 // will not observe it anyway.
195 f
:= float64(r
.Int63()) / (1 << 63)
197 goto again
// resample; this branch is taken O(never)
202 // Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0).
203 func (r
*Rand
) Float32() float32 {
204 // Same rationale as in Float64: we want to preserve the Go 1 value
205 // stream except we want to fix it not to return 1.0
206 // This only happens 1/2²⁴ of the time (plus the 1/2⁵³ of the time in Float64).
208 f
:= float32(r
.Float64())
210 goto again
// resample; this branch is taken O(very rarely)
215 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
216 // in the half-open interval [0,n).
217 func (r
*Rand
) Perm(n
int) []int {
219 // In the following loop, the iteration when i=0 always swaps m[0] with m[0].
220 // A change to remove this useless iteration is to assign 1 to i in the init
221 // statement. But Perm also effects r. Making this change will affect
222 // the final state of r. So this change can't be made for compatibility
224 for i
:= 0; i
< n
; i
++ {
232 // Shuffle pseudo-randomizes the order of elements.
233 // n is the number of elements. Shuffle panics if n < 0.
234 // swap swaps the elements with indexes i and j.
235 func (r
*Rand
) Shuffle(n
int, swap
func(i
, j
int)) {
237 panic("invalid argument to Shuffle")
240 // Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
241 // Shuffle really ought not be called with n that doesn't fit in 32 bits.
242 // Not only will it take a very long time, but with 2³¹! possible permutations,
243 // there's no way that any PRNG can have a big enough internal state to
244 // generate even a minuscule percentage of the possible permutations.
245 // Nevertheless, the right API signature accepts an int n, so handle it as best we can.
247 for ; i
> 1<<31-1-1; i
-- {
248 j
:= int(r
.Int63n(int64(i
+ 1)))
252 j
:= int(r
.int31n(int32(i
+ 1)))
257 // Read generates len(p) random bytes and writes them into p. It
258 // always returns len(p) and a nil error.
259 // Read should not be called concurrently with any other Rand method.
260 func (r
*Rand
) Read(p
[]byte) (n
int, err error
) {
261 if lk
, ok
:= r
.src
.(*lockedSource
); ok
{
262 return lk
.read(p
, &r
.readVal
, &r
.readPos
)
264 return read(p
, r
.src
, &r
.readVal
, &r
.readPos
)
267 func read(p
[]byte, src Source
, readVal
*int64, readPos
*int8) (n
int, err error
) {
270 rng
, _
:= src
.(*rngSource
)
271 for n
= 0; n
< len(p
); n
++ {
290 * Top-level convenience functions
293 var globalRand
= New(&lockedSource
{src
: NewSource(1).(*rngSource
)})
295 // Type assert that globalRand's source is a lockedSource whose src is a *rngSource.
296 var _
*rngSource
= globalRand
.src
.(*lockedSource
).src
298 // Seed uses the provided seed value to initialize the default Source to a
299 // deterministic state. If Seed is not called, the generator behaves as
300 // if seeded by Seed(1). Seed values that have the same remainder when
301 // divided by 2³¹-1 generate the same pseudo-random sequence.
302 // Seed, unlike the Rand.Seed method, is safe for concurrent use.
303 func Seed(seed
int64) { globalRand
.Seed(seed
) }
305 // Int63 returns a non-negative pseudo-random 63-bit integer as an int64
306 // from the default Source.
307 func Int63() int64 { return globalRand
.Int63() }
309 // Uint32 returns a pseudo-random 32-bit value as a uint32
310 // from the default Source.
311 func Uint32() uint32 { return globalRand
.Uint32() }
313 // Uint64 returns a pseudo-random 64-bit value as a uint64
314 // from the default Source.
315 func Uint64() uint64 { return globalRand
.Uint64() }
317 // Int31 returns a non-negative pseudo-random 31-bit integer as an int32
318 // from the default Source.
319 func Int31() int32 { return globalRand
.Int31() }
321 // Int returns a non-negative pseudo-random int from the default Source.
322 func Int() int { return globalRand
.Int() }
324 // Int63n returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n)
325 // from the default Source.
326 // It panics if n <= 0.
327 func Int63n(n
int64) int64 { return globalRand
.Int63n(n
) }
329 // Int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n)
330 // from the default Source.
331 // It panics if n <= 0.
332 func Int31n(n
int32) int32 { return globalRand
.Int31n(n
) }
334 // Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n)
335 // from the default Source.
336 // It panics if n <= 0.
337 func Intn(n
int) int { return globalRand
.Intn(n
) }
339 // Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0)
340 // from the default Source.
341 func Float64() float64 { return globalRand
.Float64() }
343 // Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0)
344 // from the default Source.
345 func Float32() float32 { return globalRand
.Float32() }
347 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
348 // in the half-open interval [0,n) from the default Source.
349 func Perm(n
int) []int { return globalRand
.Perm(n
) }
351 // Shuffle pseudo-randomizes the order of elements using the default Source.
352 // n is the number of elements. Shuffle panics if n < 0.
353 // swap swaps the elements with indexes i and j.
354 func Shuffle(n
int, swap
func(i
, j
int)) { globalRand
.Shuffle(n
, swap
) }
356 // Read generates len(p) random bytes from the default Source and
357 // writes them into p. It always returns len(p) and a nil error.
358 // Read, unlike the Rand.Read method, is safe for concurrent use.
359 func Read(p
[]byte) (n
int, err error
) { return globalRand
.Read(p
) }
361 // NormFloat64 returns a normally distributed float64 in the range
362 // [-math.MaxFloat64, +math.MaxFloat64] with
363 // standard normal distribution (mean = 0, stddev = 1)
364 // from the default Source.
365 // To produce a different normal distribution, callers can
366 // adjust the output using:
368 // sample = NormFloat64() * desiredStdDev + desiredMean
370 func NormFloat64() float64 { return globalRand
.NormFloat64() }
372 // ExpFloat64 returns an exponentially distributed float64 in the range
373 // (0, +math.MaxFloat64] with an exponential distribution whose rate parameter
374 // (lambda) is 1 and whose mean is 1/lambda (1) from the default Source.
375 // To produce a distribution with a different rate parameter,
376 // callers can adjust the output using:
378 // sample = ExpFloat64() / desiredRateParameter
380 func ExpFloat64() float64 { return globalRand
.ExpFloat64() }
382 type lockedSource
struct {
387 func (r
*lockedSource
) Int63() (n
int64) {
394 func (r
*lockedSource
) Uint64() (n
uint64) {
401 func (r
*lockedSource
) Seed(seed
int64) {
407 // seedPos implements Seed for a lockedSource without a race condition.
408 func (r
*lockedSource
) seedPos(seed
int64, readPos
*int8) {
415 // read implements Read for a lockedSource without a race condition.
416 func (r
*lockedSource
) read(p
[]byte, readVal
*int64, readPos
*int8) (n
int, err error
) {
418 n
, err
= read(p
, r
.src
, readVal
, readPos
)