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 suitable for tasks
6 // such as simulation, but it should not be used for security-sensitive work.
8 // Random numbers are generated by a [Source], usually wrapped in a [Rand].
9 // Both types should be used by a single goroutine at a time: sharing among
10 // multiple goroutines requires some kind of synchronization.
12 // Top-level functions, such as [Float64] and [Int],
13 // are safe for concurrent use by multiple goroutines.
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.
21 _ "unsafe" // for go:linkname
24 // A Source represents a source of uniformly-distributed
25 // pseudo-random int64 values in the range [0, 1<<63).
27 // A Source is not safe for concurrent use by multiple goroutines.
28 type Source interface {
32 // A Source64 is a Source that can also generate
33 // uniformly-distributed pseudo-random uint64 values in
34 // the range [0, 1<<64) directly.
35 // If a Rand r's underlying Source s implements Source64,
36 // then r.Uint64 returns the result of one call to s.Uint64
37 // instead of making two calls to s.Int64.
38 type Source64 interface {
43 // NewSource returns a new pseudo-random Source seeded with the given value.
44 // Unlike the default Source used by top-level functions, this source is not
45 // safe for concurrent use by multiple goroutines.
46 // The returned Source implements Source64.
47 func NewSource(seed int64) Source {
48 return newSource(seed)
51 func newSource(seed int64) *rngSource {
57 // A Rand is a source of random numbers.
60 s64 Source64 // non-nil if src is source64
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}
70 // Int64 returns a non-negative pseudo-random 63-bit integer as an int64.
71 func (r *Rand) Int64() int64 { return r.src.Int64() }
73 // Uint32 returns a pseudo-random 32-bit value as a uint32.
74 func (r *Rand) Uint32() uint32 { return uint32(r.Int64() >> 31) }
76 // Uint64 returns a pseudo-random 64-bit value as a uint64.
77 func (r *Rand) Uint64() uint64 {
81 return uint64(r.Int64())>>31 | uint64(r.Int64())<<32
84 // Int32 returns a non-negative pseudo-random 31-bit integer as an int32.
85 func (r *Rand) Int32() int32 { return int32(r.Int64() >> 32) }
87 // Int returns a non-negative pseudo-random int.
88 func (r *Rand) Int() int {
90 return int(u << 1 >> 1) // clear sign bit if int == int32
93 // Int64N returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n).
94 // It panics if n <= 0.
95 func (r *Rand) Int64N(n int64) int64 {
97 panic("invalid argument to Int64N")
99 if n&(n-1) == 0 { // n is power of two, can mask
100 return r.Int64() & (n - 1)
102 max := int64((1 << 63) - 1 - (1<<63)%uint64(n))
110 // Int32N returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n).
111 // It panics if n <= 0.
112 func (r *Rand) Int32N(n int32) int32 {
114 panic("invalid argument to Int32N")
116 if n&(n-1) == 0 { // n is power of two, can mask
117 return r.Int32() & (n - 1)
119 max := int32((1 << 31) - 1 - (1<<31)%uint32(n))
127 // int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n).
128 // n must be > 0, but int31n does not check this; the caller must ensure it.
129 // int31n exists because Int32N is inefficient, but Go 1 compatibility
130 // requires that the stream of values produced by math/rand/v2 remain unchanged.
131 // int31n can thus only be used internally, by newly introduced APIs.
133 // For implementation details, see:
134 // https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction
135 // https://lemire.me/blog/2016/06/30/fast-random-shuffling
136 func (r *Rand) int31n(n int32) int32 {
138 prod := uint64(v) * uint64(n)
141 thresh := uint32(-n) % uint32(n)
144 prod = uint64(v) * uint64(n)
148 return int32(prod >> 32)
151 // IntN returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n).
152 // It panics if n <= 0.
153 func (r *Rand) IntN(n int) int {
155 panic("invalid argument to IntN")
158 return int(r.Int32N(int32(n)))
160 return int(r.Int64N(int64(n)))
163 // Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0).
164 func (r *Rand) Float64() float64 {
165 // A clearer, simpler implementation would be:
166 // return float64(r.Int64N(1<<53)) / (1<<53)
167 // However, Go 1 shipped with
168 // return float64(r.Int64()) / (1 << 63)
169 // and we want to preserve that value stream.
171 // There is one bug in the value stream: r.Int64() may be so close
172 // to 1<<63 that the division rounds up to 1.0, and we've guaranteed
173 // that the result is always less than 1.0.
175 // We tried to fix this by mapping 1.0 back to 0.0, but since float64
176 // values near 0 are much denser than near 1, mapping 1 to 0 caused
177 // a theoretically significant overshoot in the probability of returning 0.
178 // Instead of that, if we round up to 1, just try again.
179 // Getting 1 only happens 1/2⁵³ of the time, so most clients
180 // will not observe it anyway.
182 f := float64(r.Int64()) / (1 << 63)
184 goto again // resample; this branch is taken O(never)
189 // Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0).
190 func (r *Rand) Float32() float32 {
191 // Same rationale as in Float64: we want to preserve the Go 1 value
192 // stream except we want to fix it not to return 1.0
193 // This only happens 1/2²⁴ of the time (plus the 1/2⁵³ of the time in Float64).
195 f := float32(r.Float64())
197 goto again // resample; this branch is taken O(very rarely)
202 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
203 // in the half-open interval [0,n).
204 func (r *Rand) Perm(n int) []int {
206 // In the following loop, the iteration when i=0 always swaps m[0] with m[0].
207 // A change to remove this useless iteration is to assign 1 to i in the init
208 // statement. But Perm also effects r. Making this change will affect
209 // the final state of r. So this change can't be made for compatibility
211 for i := 0; i < n; i++ {
219 // Shuffle pseudo-randomizes the order of elements.
220 // n is the number of elements. Shuffle panics if n < 0.
221 // swap swaps the elements with indexes i and j.
222 func (r *Rand) Shuffle(n int, swap func(i, j int)) {
224 panic("invalid argument to Shuffle")
227 // Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
228 // Shuffle really ought not be called with n that doesn't fit in 32 bits.
229 // Not only will it take a very long time, but with 2³¹! possible permutations,
230 // there's no way that any PRNG can have a big enough internal state to
231 // generate even a minuscule percentage of the possible permutations.
232 // Nevertheless, the right API signature accepts an int n, so handle it as best we can.
234 for ; i > 1<<31-1-1; i-- {
235 j := int(r.Int64N(int64(i + 1)))
239 j := int(r.int31n(int32(i + 1)))
245 * Top-level convenience functions
248 // globalRand is the source of random numbers for the top-level
249 // convenience functions.
250 var globalRand = &Rand{src: &fastSource{}}
252 //go:linkname fastrand64
253 func fastrand64() uint64
255 // fastSource is a Source that uses the runtime fastrand functions.
256 type fastSource struct{}
258 func (*fastSource) Int64() int64 {
259 return int64(fastrand64() & rngMask)
262 func (*fastSource) Uint64() uint64 {
266 // Int64 returns a non-negative pseudo-random 63-bit integer as an int64
267 // from the default Source.
268 func Int64() int64 { return globalRand.Int64() }
270 // Uint32 returns a pseudo-random 32-bit value as a uint32
271 // from the default Source.
272 func Uint32() uint32 { return globalRand.Uint32() }
274 // Uint64 returns a pseudo-random 64-bit value as a uint64
275 // from the default Source.
276 func Uint64() uint64 { return globalRand.Uint64() }
278 // Int32 returns a non-negative pseudo-random 31-bit integer as an int32
279 // from the default Source.
280 func Int32() int32 { return globalRand.Int32() }
282 // Int returns a non-negative pseudo-random int from the default Source.
283 func Int() int { return globalRand.Int() }
285 // Int64N returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n)
286 // from the default Source.
287 // It panics if n <= 0.
288 func Int64N(n int64) int64 { return globalRand.Int64N(n) }
290 // Int32N returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n)
291 // from the default Source.
292 // It panics if n <= 0.
293 func Int32N(n int32) int32 { return globalRand.Int32N(n) }
295 // IntN returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n)
296 // from the default Source.
297 // It panics if n <= 0.
298 func IntN(n int) int { return globalRand.IntN(n) }
300 // Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0)
301 // from the default Source.
302 func Float64() float64 { return globalRand.Float64() }
304 // Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0)
305 // from the default Source.
306 func Float32() float32 { return globalRand.Float32() }
308 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
309 // in the half-open interval [0,n) from the default Source.
310 func Perm(n int) []int { return globalRand.Perm(n) }
312 // Shuffle pseudo-randomizes the order of elements using the default Source.
313 // n is the number of elements. Shuffle panics if n < 0.
314 // swap swaps the elements with indexes i and j.
315 func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }
317 // NormFloat64 returns a normally distributed float64 in the range
318 // [-math.MaxFloat64, +math.MaxFloat64] with
319 // standard normal distribution (mean = 0, stddev = 1)
320 // from the default Source.
321 // To produce a different normal distribution, callers can
322 // adjust the output using:
324 // sample = NormFloat64() * desiredStdDev + desiredMean
325 func NormFloat64() float64 { return globalRand.NormFloat64() }
327 // ExpFloat64 returns an exponentially distributed float64 in the range
328 // (0, +math.MaxFloat64] with an exponential distribution whose rate parameter
329 // (lambda) is 1 and whose mean is 1/lambda (1) from the default Source.
330 // To produce a distribution with a different rate parameter,
331 // callers can adjust the output using:
333 // sample = ExpFloat64() / desiredRateParameter
334 func ExpFloat64() float64 { return globalRand.ExpFloat64() }