]> Cypherpunks.ru repositories - gostls13.git/blob - src/math/rand/v2/rand.go
c6030f77fc8b5e998d94681495dc77c5246ffd9f
[gostls13.git] / src / math / rand / v2 / rand.go
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 suitable for tasks
6 // such as simulation, but it should not be used for security-sensitive work.
7 //
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.
11 //
12 // Top-level functions, such as [Float64] and [Int],
13 // are safe for concurrent use by multiple goroutines.
14 //
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.
18 package rand
19
20 import (
21         "math/bits"
22         _ "unsafe" // for go:linkname
23 )
24
25 // A Source is a source of uniformly-distributed
26 // pseudo-random uint64 values in the range [0, 1<<64).
27 //
28 // A Source is not safe for concurrent use by multiple goroutines.
29 type Source interface {
30         Uint64() uint64
31 }
32
33 // NewSource returns a new pseudo-random Source seeded with the given value.
34 // Unlike the default Source used by top-level functions, this source is not
35 // safe for concurrent use by multiple goroutines.
36 // The returned Source implements Source64.
37 func NewSource(seed int64) Source {
38         return newSource(seed)
39 }
40
41 func newSource(seed int64) *rngSource {
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 }
51
52 // New returns a new Rand that uses random values from src
53 // to generate other random values.
54 func New(src Source) *Rand {
55         return &Rand{src: src}
56 }
57
58 // Int64 returns a non-negative pseudo-random 63-bit integer as an int64.
59 func (r *Rand) Int64() int64 { return int64(r.src.Uint64() &^ (1 << 63)) }
60
61 // Uint32 returns a pseudo-random 32-bit value as a uint32.
62 func (r *Rand) Uint32() uint32 { return uint32(r.src.Uint64() >> 32) }
63
64 // Uint64 returns a pseudo-random 64-bit value as a uint64.
65 func (r *Rand) Uint64() uint64 { return r.src.Uint64() }
66
67 // Int32 returns a non-negative pseudo-random 31-bit integer as an int32.
68 func (r *Rand) Int32() int32 { return int32(r.src.Uint64() >> 33) }
69
70 // Int returns a non-negative pseudo-random int.
71 func (r *Rand) Int() int { return int(uint(r.src.Uint64()) << 1 >> 1) }
72
73 // Int64N returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n).
74 // It panics if n <= 0.
75 func (r *Rand) Int64N(n int64) int64 {
76         if n <= 0 {
77                 panic("invalid argument to Int64N")
78         }
79         return int64(r.uint64n(uint64(n)))
80 }
81
82 // Uint64N returns, as a uint64, a non-negative pseudo-random number in the half-open interval [0,n).
83 // It panics if n == 0.
84 func (r *Rand) Uint64N(n uint64) uint64 {
85         if n == 0 {
86                 panic("invalid argument to Uint64N")
87         }
88         return r.uint64n(n)
89 }
90
91 // uint64n is the no-bounds-checks version of Uint64N.
92 func (r *Rand) uint64n(n uint64) uint64 {
93         if is32bit && uint64(uint32(n)) == n {
94                 return uint64(r.uint32n(uint32(n)))
95         }
96         if n&(n-1) == 0 { // n is power of two, can mask
97                 return r.Uint64() & (n - 1)
98         }
99
100         // Suppose we have a uint64 x uniform in the range [0,2⁶⁴)
101         // and want to reduce it to the range [0,n) preserving exact uniformity.
102         // We can simulate a scaling arbitrary precision x * (n/2⁶⁴) by
103         // the high bits of a double-width multiply of x*n, meaning (x*n)/2⁶⁴.
104         // Since there are 2⁶⁴ possible inputs x and only n possible outputs,
105         // the output is necessarily biased if n does not divide 2⁶⁴.
106         // In general (x*n)/2⁶⁴ = k for x*n in [k*2⁶⁴,(k+1)*2⁶⁴).
107         // There are either floor(2⁶⁴/n) or ceil(2⁶⁴/n) possible products
108         // in that range, depending on k.
109         // But suppose we reject the sample and try again when
110         // x*n is in [k*2⁶⁴, k*2⁶⁴+(2⁶⁴%n)), meaning rejecting fewer than n possible
111         // outcomes out of the 2⁶⁴.
112         // Now there are exactly floor(2⁶⁴/n) possible ways to produce
113         // each output value k, so we've restored uniformity.
114         // To get valid uint64 math, 2⁶⁴ % n = (2⁶⁴ - n) % n = -n % n,
115         // so the direct implementation of this algorithm would be:
116         //
117         //      hi, lo := bits.Mul64(r.Uint64(), n)
118         //      thresh := -n % n
119         //      for lo < thresh {
120         //              hi, lo = bits.Mul64(r.Uint64(), n)
121         //      }
122         //
123         // That still leaves an expensive 64-bit division that we would rather avoid.
124         // We know that thresh < n, and n is usually much less than 2⁶⁴, so we can
125         // avoid the last four lines unless lo < n.
126         //
127         // See also:
128         // https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction
129         // https://lemire.me/blog/2016/06/30/fast-random-shuffling
130         hi, lo := bits.Mul64(r.Uint64(), n)
131         if lo < n {
132                 thresh := -n % n
133                 for lo < thresh {
134                         hi, lo = bits.Mul64(r.Uint64(), n)
135                 }
136         }
137         return hi
138 }
139
140 // uint32n is an identical computation to uint64n
141 // but optimized for 32-bit systems.
142 func (r *Rand) uint32n(n uint32) uint32 {
143         if n&(n-1) == 0 { // n is power of two, can mask
144                 return uint32(r.Uint64()) & (n - 1)
145         }
146         // On 64-bit systems we still use the uint64 code below because
147         // the probability of a random uint64 lo being < a uint32 n is near zero,
148         // meaning the unbiasing loop almost never runs.
149         // On 32-bit systems, here we need to implement that same logic in 32-bit math,
150         // both to preserve the exact output sequence observed on 64-bit machines
151         // and to preserve the optimization that the unbiasing loop almost never runs.
152         //
153         // We want to compute
154         //      hi, lo := bits.Mul64(r.Uint64(), n)
155         // In terms of 32-bit halves, this is:
156         //      x1:x0 := r.Uint64()
157         //      0:hi, lo1:lo0 := bits.Mul64(x1:x0, 0:n)
158         // Writing out the multiplication in terms of bits.Mul32 allows
159         // using direct hardware instructions and avoiding
160         // the computations involving these zeros.
161         x := r.Uint64()
162         lo1a, lo0 := bits.Mul32(uint32(x), n)
163         hi, lo1b := bits.Mul32(uint32(x>>32), n)
164         lo1, c := bits.Add32(lo1a, lo1b, 0)
165         hi += c
166         if lo1 == 0 && lo0 < uint32(n) {
167                 n64 := uint64(n)
168                 thresh := uint32(-n64 % n64)
169                 for lo1 == 0 && lo0 < thresh {
170                         x := r.Uint64()
171                         lo1a, lo0 = bits.Mul32(uint32(x), n)
172                         hi, lo1b = bits.Mul32(uint32(x>>32), n)
173                         lo1, c = bits.Add32(lo1a, lo1b, 0)
174                         hi += c
175                 }
176         }
177         return hi
178 }
179
180 // Int32N returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n).
181 // It panics if n <= 0.
182 func (r *Rand) Int32N(n int32) int32 {
183         if n <= 0 {
184                 panic("invalid argument to Int32N")
185         }
186         return int32(r.uint64n(uint64(n)))
187 }
188
189 // Uint32N returns, as a uint32, a non-negative pseudo-random number in the half-open interval [0,n).
190 // It panics if n == 0.
191 func (r *Rand) Uint32N(n uint32) uint32 {
192         if n == 0 {
193                 panic("invalid argument to Uint32N")
194         }
195         return uint32(r.uint64n(uint64(n)))
196 }
197
198 const is32bit = ^uint(0)>>32 == 0
199
200 // IntN returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n).
201 // It panics if n <= 0.
202 func (r *Rand) IntN(n int) int {
203         if n <= 0 {
204                 panic("invalid argument to IntN")
205         }
206         return int(r.uint64n(uint64(n)))
207 }
208
209 // UintN returns, as a uint, a non-negative pseudo-random number in the half-open interval [0,n).
210 // It panics if n == 0.
211 func (r *Rand) UintN(n uint) uint {
212         if n == 0 {
213                 panic("invalid argument to UintN")
214         }
215         return uint(r.uint64n(uint64(n)))
216 }
217
218 // Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0).
219 func (r *Rand) Float64() float64 {
220         // There are exactly 1<<53 float64s in [0,1). Use Intn(1<<53) / (1<<53).
221         return float64(r.Uint64()<<11>>11) / (1 << 53)
222 }
223
224 // Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0).
225 func (r *Rand) Float32() float32 {
226         // There are exactly 1<<24 float32s in [0,1). Use Intn(1<<24) / (1<<24).
227         return float32(r.Uint32()<<8>>8) / (1 << 24)
228 }
229
230 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
231 // in the half-open interval [0,n).
232 func (r *Rand) Perm(n int) []int {
233         p := make([]int, n)
234         for i := range p {
235                 p[i] = i
236         }
237         r.Shuffle(len(p), func(i, j int) { p[i], p[j] = p[j], p[i] })
238         return p
239 }
240
241 // Shuffle pseudo-randomizes the order of elements.
242 // n is the number of elements. Shuffle panics if n < 0.
243 // swap swaps the elements with indexes i and j.
244 func (r *Rand) Shuffle(n int, swap func(i, j int)) {
245         if n < 0 {
246                 panic("invalid argument to Shuffle")
247         }
248
249         // Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
250         // Shuffle really ought not be called with n that doesn't fit in 32 bits.
251         // Not only will it take a very long time, but with 2³¹! possible permutations,
252         // there's no way that any PRNG can have a big enough internal state to
253         // generate even a minuscule percentage of the possible permutations.
254         // Nevertheless, the right API signature accepts an int n, so handle it as best we can.
255         for i := n - 1; i > 0; i-- {
256                 j := int(r.uint64n(uint64(i + 1)))
257                 swap(i, j)
258         }
259 }
260
261 /*
262  * Top-level convenience functions
263  */
264
265 // globalRand is the source of random numbers for the top-level
266 // convenience functions.
267 var globalRand = &Rand{src: &fastSource{}}
268
269 //go:linkname fastrand64
270 func fastrand64() uint64
271
272 // fastSource is a Source that uses the runtime fastrand functions.
273 type fastSource struct{}
274
275 func (*fastSource) Int64() int64 {
276         return int64(fastrand64() & rngMask)
277 }
278
279 func (*fastSource) Uint64() uint64 {
280         return fastrand64()
281 }
282
283 // Int64 returns a non-negative pseudo-random 63-bit integer as an int64
284 // from the default Source.
285 func Int64() int64 { return globalRand.Int64() }
286
287 // Uint32 returns a pseudo-random 32-bit value as a uint32
288 // from the default Source.
289 func Uint32() uint32 { return globalRand.Uint32() }
290
291 // Uint64N returns, as a uint64, a pseudo-random number in the half-open interval [0,n)
292 // from the default Source.
293 // It panics if n <= 0.
294 func Uint64N(n uint64) uint64 { return globalRand.Uint64N(n) }
295
296 // Uint32N returns, as a uint32, a pseudo-random number in the half-open interval [0,n)
297 // from the default Source.
298 // It panics if n <= 0.
299 func Uint32N(n uint32) uint32 { return globalRand.Uint32N(n) }
300
301 // Uint64 returns a pseudo-random 64-bit value as a uint64
302 // from the default Source.
303 func Uint64() uint64 { return globalRand.Uint64() }
304
305 // Int32 returns a non-negative pseudo-random 31-bit integer as an int32
306 // from the default Source.
307 func Int32() int32 { return globalRand.Int32() }
308
309 // Int returns a non-negative pseudo-random int from the default Source.
310 func Int() int { return globalRand.Int() }
311
312 // Int64N returns, as an int64, a pseudo-random number in the half-open interval [0,n)
313 // from the default Source.
314 // It panics if n <= 0.
315 func Int64N(n int64) int64 { return globalRand.Int64N(n) }
316
317 // Int32N returns, as an int32, a pseudo-random number in the half-open interval [0,n)
318 // from the default Source.
319 // It panics if n <= 0.
320 func Int32N(n int32) int32 { return globalRand.Int32N(n) }
321
322 // IntN returns, as an int, a pseudo-random number in the half-open interval [0,n)
323 // from the default Source.
324 // It panics if n <= 0.
325 func IntN(n int) int { return globalRand.IntN(n) }
326
327 // UintN returns, as a uint, a pseudo-random number in the half-open interval [0,n)
328 // from the default Source.
329 // It panics if n <= 0.
330 func UintN(n uint) uint { return globalRand.UintN(n) }
331
332 // N returns a pseudo-random number in the half-open interval [0,n) from the default Source.
333 // The type parameter Int can be any integer type.
334 // It panics if n <= 0.
335 func N[Int intType](n Int) Int {
336         if n <= 0 {
337                 panic("invalid argument to N")
338         }
339         return Int(globalRand.uint64n(uint64(n)))
340 }
341
342 type intType interface {
343         ~int | ~int8 | ~int16 | ~int32 | ~int64 |
344                 ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
345 }
346
347 // Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0)
348 // from the default Source.
349 func Float64() float64 { return globalRand.Float64() }
350
351 // Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0)
352 // from the default Source.
353 func Float32() float32 { return globalRand.Float32() }
354
355 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
356 // in the half-open interval [0,n) from the default Source.
357 func Perm(n int) []int { return globalRand.Perm(n) }
358
359 // Shuffle pseudo-randomizes the order of elements using the default Source.
360 // n is the number of elements. Shuffle panics if n < 0.
361 // swap swaps the elements with indexes i and j.
362 func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }
363
364 // NormFloat64 returns a normally distributed float64 in the range
365 // [-math.MaxFloat64, +math.MaxFloat64] with
366 // standard normal distribution (mean = 0, stddev = 1)
367 // from the default Source.
368 // To produce a different normal distribution, callers can
369 // adjust the output using:
370 //
371 //      sample = NormFloat64() * desiredStdDev + desiredMean
372 func NormFloat64() float64 { return globalRand.NormFloat64() }
373
374 // ExpFloat64 returns an exponentially distributed float64 in the range
375 // (0, +math.MaxFloat64] with an exponential distribution whose rate parameter
376 // (lambda) is 1 and whose mean is 1/lambda (1) from the default Source.
377 // To produce a distribution with a different rate parameter,
378 // callers can adjust the output using:
379 //
380 //      sample = ExpFloat64() / desiredRateParameter
381 func ExpFloat64() float64 { return globalRand.ExpFloat64() }