]> Cypherpunks.ru repositories - gostls13.git/blob - src/math/rand/v2/rand.go
math/rand/v2: change Source to use uint64
[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         _ "unsafe" // for go:linkname
22 )
23
24 // A Source is a source of uniformly-distributed
25 // pseudo-random uint64 values in the range [0, 1<<64).
26 //
27 // A Source is not safe for concurrent use by multiple goroutines.
28 type Source interface {
29         Uint64() uint64
30 }
31
32 // NewSource returns a new pseudo-random Source seeded with the given value.
33 // Unlike the default Source used by top-level functions, this source is not
34 // safe for concurrent use by multiple goroutines.
35 // The returned Source implements Source64.
36 func NewSource(seed int64) Source {
37         return newSource(seed)
38 }
39
40 func newSource(seed int64) *rngSource {
41         var rng rngSource
42         rng.Seed(seed)
43         return &rng
44 }
45
46 // A Rand is a source of random numbers.
47 type Rand struct {
48         src Source
49 }
50
51 // New returns a new Rand that uses random values from src
52 // to generate other random values.
53 func New(src Source) *Rand {
54         return &Rand{src: src}
55 }
56
57 // Int64 returns a non-negative pseudo-random 63-bit integer as an int64.
58 func (r *Rand) Int64() int64 { return int64(r.src.Uint64() &^ (1 << 63)) }
59
60 // Uint32 returns a pseudo-random 32-bit value as a uint32.
61 func (r *Rand) Uint32() uint32 { return uint32(r.Int64() >> 31) }
62
63 // Uint64 returns a pseudo-random 64-bit value as a uint64.
64 func (r *Rand) Uint64() uint64 {
65         return r.src.Uint64()
66 }
67
68 // Int32 returns a non-negative pseudo-random 31-bit integer as an int32.
69 func (r *Rand) Int32() int32 { return int32(r.Int64() >> 32) }
70
71 // Int returns a non-negative pseudo-random int.
72 func (r *Rand) Int() int {
73         u := uint(r.Int64())
74         return int(u << 1 >> 1) // clear sign bit if int == int32
75 }
76
77 // Int64N returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n).
78 // It panics if n <= 0.
79 func (r *Rand) Int64N(n int64) int64 {
80         if n <= 0 {
81                 panic("invalid argument to Int64N")
82         }
83         if n&(n-1) == 0 { // n is power of two, can mask
84                 return r.Int64() & (n - 1)
85         }
86         max := int64((1 << 63) - 1 - (1<<63)%uint64(n))
87         v := r.Int64()
88         for v > max {
89                 v = r.Int64()
90         }
91         return v % n
92 }
93
94 // Int32N returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n).
95 // It panics if n <= 0.
96 func (r *Rand) Int32N(n int32) int32 {
97         if n <= 0 {
98                 panic("invalid argument to Int32N")
99         }
100         if n&(n-1) == 0 { // n is power of two, can mask
101                 return r.Int32() & (n - 1)
102         }
103         max := int32((1 << 31) - 1 - (1<<31)%uint32(n))
104         v := r.Int32()
105         for v > max {
106                 v = r.Int32()
107         }
108         return v % n
109 }
110
111 // int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n).
112 // n must be > 0, but int31n does not check this; the caller must ensure it.
113 // int31n exists because Int32N is inefficient, but Go 1 compatibility
114 // requires that the stream of values produced by math/rand/v2 remain unchanged.
115 // int31n can thus only be used internally, by newly introduced APIs.
116 //
117 // For implementation details, see:
118 // https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction
119 // https://lemire.me/blog/2016/06/30/fast-random-shuffling
120 func (r *Rand) int31n(n int32) int32 {
121         v := r.Uint32()
122         prod := uint64(v) * uint64(n)
123         low := uint32(prod)
124         if low < uint32(n) {
125                 thresh := uint32(-n) % uint32(n)
126                 for low < thresh {
127                         v = r.Uint32()
128                         prod = uint64(v) * uint64(n)
129                         low = uint32(prod)
130                 }
131         }
132         return int32(prod >> 32)
133 }
134
135 // IntN returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n).
136 // It panics if n <= 0.
137 func (r *Rand) IntN(n int) int {
138         if n <= 0 {
139                 panic("invalid argument to IntN")
140         }
141         if n <= 1<<31-1 {
142                 return int(r.Int32N(int32(n)))
143         }
144         return int(r.Int64N(int64(n)))
145 }
146
147 // Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0).
148 func (r *Rand) Float64() float64 {
149         // A clearer, simpler implementation would be:
150         //      return float64(r.Int64N(1<<53)) / (1<<53)
151         // However, Go 1 shipped with
152         //      return float64(r.Int64()) / (1 << 63)
153         // and we want to preserve that value stream.
154         //
155         // There is one bug in the value stream: r.Int64() may be so close
156         // to 1<<63 that the division rounds up to 1.0, and we've guaranteed
157         // that the result is always less than 1.0.
158         //
159         // We tried to fix this by mapping 1.0 back to 0.0, but since float64
160         // values near 0 are much denser than near 1, mapping 1 to 0 caused
161         // a theoretically significant overshoot in the probability of returning 0.
162         // Instead of that, if we round up to 1, just try again.
163         // Getting 1 only happens 1/2⁵³ of the time, so most clients
164         // will not observe it anyway.
165 again:
166         f := float64(r.Int64()) / (1 << 63)
167         if f == 1 {
168                 goto again // resample; this branch is taken O(never)
169         }
170         return f
171 }
172
173 // Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0).
174 func (r *Rand) Float32() float32 {
175         // Same rationale as in Float64: we want to preserve the Go 1 value
176         // stream except we want to fix it not to return 1.0
177         // This only happens 1/2²⁴ of the time (plus the 1/2⁵³ of the time in Float64).
178 again:
179         f := float32(r.Float64())
180         if f == 1 {
181                 goto again // resample; this branch is taken O(very rarely)
182         }
183         return f
184 }
185
186 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
187 // in the half-open interval [0,n).
188 func (r *Rand) Perm(n int) []int {
189         m := make([]int, n)
190         // In the following loop, the iteration when i=0 always swaps m[0] with m[0].
191         // A change to remove this useless iteration is to assign 1 to i in the init
192         // statement. But Perm also effects r. Making this change will affect
193         // the final state of r. So this change can't be made for compatibility
194         // reasons for Go 1.
195         for i := 0; i < n; i++ {
196                 j := r.IntN(i + 1)
197                 m[i] = m[j]
198                 m[j] = i
199         }
200         return m
201 }
202
203 // Shuffle pseudo-randomizes the order of elements.
204 // n is the number of elements. Shuffle panics if n < 0.
205 // swap swaps the elements with indexes i and j.
206 func (r *Rand) Shuffle(n int, swap func(i, j int)) {
207         if n < 0 {
208                 panic("invalid argument to Shuffle")
209         }
210
211         // Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
212         // Shuffle really ought not be called with n that doesn't fit in 32 bits.
213         // Not only will it take a very long time, but with 2³¹! possible permutations,
214         // there's no way that any PRNG can have a big enough internal state to
215         // generate even a minuscule percentage of the possible permutations.
216         // Nevertheless, the right API signature accepts an int n, so handle it as best we can.
217         i := n - 1
218         for ; i > 1<<31-1-1; i-- {
219                 j := int(r.Int64N(int64(i + 1)))
220                 swap(i, j)
221         }
222         for ; i > 0; i-- {
223                 j := int(r.int31n(int32(i + 1)))
224                 swap(i, j)
225         }
226 }
227
228 /*
229  * Top-level convenience functions
230  */
231
232 // globalRand is the source of random numbers for the top-level
233 // convenience functions.
234 var globalRand = &Rand{src: &fastSource{}}
235
236 //go:linkname fastrand64
237 func fastrand64() uint64
238
239 // fastSource is a Source that uses the runtime fastrand functions.
240 type fastSource struct{}
241
242 func (*fastSource) Int64() int64 {
243         return int64(fastrand64() & rngMask)
244 }
245
246 func (*fastSource) Uint64() uint64 {
247         return fastrand64()
248 }
249
250 // Int64 returns a non-negative pseudo-random 63-bit integer as an int64
251 // from the default Source.
252 func Int64() int64 { return globalRand.Int64() }
253
254 // Uint32 returns a pseudo-random 32-bit value as a uint32
255 // from the default Source.
256 func Uint32() uint32 { return globalRand.Uint32() }
257
258 // Uint64 returns a pseudo-random 64-bit value as a uint64
259 // from the default Source.
260 func Uint64() uint64 { return globalRand.Uint64() }
261
262 // Int32 returns a non-negative pseudo-random 31-bit integer as an int32
263 // from the default Source.
264 func Int32() int32 { return globalRand.Int32() }
265
266 // Int returns a non-negative pseudo-random int from the default Source.
267 func Int() int { return globalRand.Int() }
268
269 // Int64N returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n)
270 // from the default Source.
271 // It panics if n <= 0.
272 func Int64N(n int64) int64 { return globalRand.Int64N(n) }
273
274 // Int32N returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n)
275 // from the default Source.
276 // It panics if n <= 0.
277 func Int32N(n int32) int32 { return globalRand.Int32N(n) }
278
279 // IntN returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n)
280 // from the default Source.
281 // It panics if n <= 0.
282 func IntN(n int) int { return globalRand.IntN(n) }
283
284 // Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0)
285 // from the default Source.
286 func Float64() float64 { return globalRand.Float64() }
287
288 // Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0)
289 // from the default Source.
290 func Float32() float32 { return globalRand.Float32() }
291
292 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
293 // in the half-open interval [0,n) from the default Source.
294 func Perm(n int) []int { return globalRand.Perm(n) }
295
296 // Shuffle pseudo-randomizes the order of elements using the default Source.
297 // n is the number of elements. Shuffle panics if n < 0.
298 // swap swaps the elements with indexes i and j.
299 func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }
300
301 // NormFloat64 returns a normally distributed float64 in the range
302 // [-math.MaxFloat64, +math.MaxFloat64] with
303 // standard normal distribution (mean = 0, stddev = 1)
304 // from the default Source.
305 // To produce a different normal distribution, callers can
306 // adjust the output using:
307 //
308 //      sample = NormFloat64() * desiredStdDev + desiredMean
309 func NormFloat64() float64 { return globalRand.NormFloat64() }
310
311 // ExpFloat64 returns an exponentially distributed float64 in the range
312 // (0, +math.MaxFloat64] with an exponential distribution whose rate parameter
313 // (lambda) is 1 and whose mean is 1/lambda (1) from the default Source.
314 // To produce a distribution with a different rate parameter,
315 // callers can adjust the output using:
316 //
317 //      sample = ExpFloat64() / desiredRateParameter
318 func ExpFloat64() float64 { return globalRand.ExpFloat64() }