Debian Codegraph @

rand/rand.go

raw symbols SCIP
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 // For random numbers suitable for security-sensitive work, see the crypto/rand
8 // package.
9 //
10 // Deprecated: use the math/rand/v2 package instead. This package is
11 // scheduled to be tagged and deleted, per https://go.dev/issue/61716.
12 package rand
13
14 import "sync"
15
16 // A Source represents a source of uniformly-distributed
17 // pseudo-random int64 values in the range [0, 1<<64).
18 type Source interface {
19 Uint64() uint64
20 Seed(seed uint64)
21 }
22
23 // NewSource returns a new pseudo-random Source seeded with the given value.
24 func NewSource(seed uint64) Source {
25 var rng PCGSource
26 rng.Seed(seed)
27 return &rng
28 }
29
30 // A Rand is a source of random numbers.
31 type Rand struct {
32 src Source
33
34 // readVal contains remainder of 64-bit integer used for bytes
35 // generation during most recent Read call.
36 // It is saved so next Read call can start where the previous
37 // one finished.
38 readVal uint64
39 // readPos indicates the number of low-order bytes of readVal
40 // that are still valid.
41 readPos int8
42 }
43
44 // New returns a new Rand that uses random values from src
45 // to generate other random values.
46 func New(src Source) *Rand {
47 return &Rand{src: src}
48 }
49
50 // Seed uses the provided seed value to initialize the generator to a deterministic state.
51 // Seed should not be called concurrently with any other Rand method.
52 func (r *Rand) Seed(seed uint64) {
53 if lk, ok := r.src.(*LockedSource); ok {
54 lk.seedPos(seed, &r.readPos)
55 return
56 }
57
58 r.src.Seed(seed)
59 r.readPos = 0
60 }
61
62 // Uint64 returns a pseudo-random 64-bit integer as a uint64.
63 func (r *Rand) Uint64() uint64 { return r.src.Uint64() }
64
65 // Int63 returns a non-negative pseudo-random 63-bit integer as an int64.
66 func (r *Rand) Int63() int64 { return int64(r.src.Uint64() &^ (1 << 63)) }
67
68 // Uint32 returns a pseudo-random 32-bit value as a uint32.
69 func (r *Rand) Uint32() uint32 { return uint32(r.Uint64() >> 32) }
70
71 // Int31 returns a non-negative pseudo-random 31-bit integer as an int32.
72 func (r *Rand) Int31() int32 { return int32(r.Uint64() >> 33) }
73
74 // Int returns a non-negative pseudo-random int.
75 func (r *Rand) Int() int {
76 u := uint(r.Uint64())
77 return int(u << 1 >> 1) // clear sign bit.
78 }
79
80 const maxUint64 = (1 << 64) - 1
81
82 // Uint64n returns, as a uint64, a pseudo-random number in [0,n).
83 // It is guaranteed more uniform than taking a Source value mod n
84 // for any n that is not a power of 2.
85 func (r *Rand) Uint64n(n uint64) uint64 {
86 if n&(n-1) == 0 { // n is power of two, can mask
87 if n == 0 {
88 panic("invalid argument to Uint64n")
89 }
90 return r.Uint64() & (n - 1)
91 }
92 // If n does not divide v, to avoid bias we must not use
93 // a v that is within maxUint64%n of the top of the range.
94 v := r.Uint64()
95 if v > maxUint64-n { // Fast check.
96 ceiling := maxUint64 - maxUint64%n
97 for v >= ceiling {
98 v = r.Uint64()
99 }
100 }
101
102 return v % n
103 }
104
105 // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n).
106 // It panics if n <= 0.
107 func (r *Rand) Int63n(n int64) int64 {
108 if n <= 0 {
109 panic("invalid argument to Int63n")
110 }
111 return int64(r.Uint64n(uint64(n)))
112 }
113
114 // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n).
115 // It panics if n <= 0.
116 func (r *Rand) Int31n(n int32) int32 {
117 if n <= 0 {
118 panic("invalid argument to Int31n")
119 }
120 // TODO: Avoid some 64-bit ops to make it more efficient on 32-bit machines.
121 return int32(r.Uint64n(uint64(n)))
122 }
123
124 // Intn returns, as an int, a non-negative pseudo-random number in [0,n).
125 // It panics if n <= 0.
126 func (r *Rand) Intn(n int) int {
127 if n <= 0 {
128 panic("invalid argument to Intn")
129 }
130 // TODO: Avoid some 64-bit ops to make it more efficient on 32-bit machines.
131 return int(r.Uint64n(uint64(n)))
132 }
133
134 // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0).
135 func (r *Rand) Float64() float64 {
136 // There is one bug in the value stream: r.Int63() may be so close
137 // to 1<<63 that the division rounds up to 1.0, and we've guaranteed
138 // that the result is always less than 1.0.
139 //
140 // We tried to fix this by mapping 1.0 back to 0.0, but since float64
141 // values near 0 are much denser than near 1, mapping 1 to 0 caused
142 // a theoretically significant overshoot in the probability of returning 0.
143 // Instead of that, if we round up to 1, just try again.
144 // Getting 1 only happens 1/2⁵³ of the time, so most clients
145 // will not observe it anyway.
146 again:
147 f := float64(r.Uint64n(1<<53)) / (1 << 53)
148 if f == 1.0 {
149 goto again // resample; this branch is taken O(never)
150 }
151 return f
152 }
153
154 // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0).
155 func (r *Rand) Float32() float32 {
156 // We do not want to return 1.0.
157 // This only happens 1/2²⁴ of the time (plus the 1/2⁵³ of the time in Float64).
158 again:
159 f := float32(r.Float64())
160 if f == 1 {
161 goto again // resample; this branch is taken O(very rarely)
162 }
163 return f
164 }
165
166 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n).
167 func (r *Rand) Perm(n int) []int {
168 m := make([]int, n)
169 // In the following loop, the iteration when i=0 always swaps m[0] with m[0].
170 // A change to remove this useless iteration is to assign 1 to i in the init
171 // statement. But Perm also effects r. Making this change will affect
172 // the final state of r. So this change can't be made for compatibility
173 // reasons for Go 1.
174 for i := 0; i < n; i++ {
175 j := r.Intn(i + 1)
176 m[i] = m[j]
177 m[j] = i
178 }
179 return m
180 }
181
182 // Shuffle pseudo-randomizes the order of elements.
183 // n is the number of elements. Shuffle panics if n < 0.
184 // swap swaps the elements with indexes i and j.
185 func (r *Rand) Shuffle(n int, swap func(i, j int)) {
186 if n < 0 {
187 panic("invalid argument to Shuffle")
188 }
189
190 // Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
191 // Shuffle really ought not be called with n that doesn't fit in 32 bits.
192 // Not only will it take a very long time, but with 2³¹! possible permutations,
193 // there's no way that any PRNG can have a big enough internal state to
194 // generate even a minuscule percentage of the possible permutations.
195 // Nevertheless, the right API signature accepts an int n, so handle it as best we can.
196 i := n - 1
197 for ; i > 1<<31-1-1; i-- {
198 j := int(r.Int63n(int64(i + 1)))
199 swap(i, j)
200 }
201 for ; i > 0; i-- {
202 j := int(r.Int31n(int32(i + 1)))
203 swap(i, j)
204 }
205 }
206
207 // Read generates len(p) random bytes and writes them into p. It
208 // always returns len(p) and a nil error.
209 // Read should not be called concurrently with any other Rand method unless
210 // the underlying source is a LockedSource.
211 func (r *Rand) Read(p []byte) (n int, err error) {
212 if lk, ok := r.src.(*LockedSource); ok {
213 return lk.Read(p, &r.readVal, &r.readPos)
214 }
215 return read(p, r.src, &r.readVal, &r.readPos)
216 }
217
218 func read(p []byte, src Source, readVal *uint64, readPos *int8) (n int, err error) {
219 pos := *readPos
220 val := *readVal
221 rng, _ := src.(*PCGSource)
222 for n = 0; n < len(p); n++ {
223 if pos == 0 {
224 if rng != nil {
225 val = rng.Uint64()
226 } else {
227 val = src.Uint64()
228 }
229 pos = 8
230 }
231 p[n] = byte(val)
232 val >>= 8
233 pos--
234 }
235 *readPos = pos
236 *readVal = val
237 return
238 }
239
240 /*
241 * Top-level convenience functions
242 */
243
244 var globalRand = New(&LockedSource{src: *NewSource(1).(*PCGSource)})
245
246 // Type assert that globalRand's source is a LockedSource whose src is a PCGSource.
247 var _ PCGSource = globalRand.src.(*LockedSource).src
248
249 // Seed uses the provided seed value to initialize the default Source to a
250 // deterministic state. If Seed is not called, the generator behaves as
251 // if seeded by Seed(1).
252 // Seed, unlike the Rand.Seed method, is safe for concurrent use.
253 func Seed(seed uint64) { globalRand.Seed(seed) }
254
255 // Int63 returns a non-negative pseudo-random 63-bit integer as an int64
256 // from the default Source.
257 func Int63() int64 { return globalRand.Int63() }
258
259 // Uint32 returns a pseudo-random 32-bit value as a uint32
260 // from the default Source.
261 func Uint32() uint32 { return globalRand.Uint32() }
262
263 // Uint64 returns a pseudo-random 64-bit value as a uint64
264 // from the default Source.
265 func Uint64() uint64 { return globalRand.Uint64() }
266
267 // Int31 returns a non-negative pseudo-random 31-bit integer as an int32
268 // from the default Source.
269 func Int31() int32 { return globalRand.Int31() }
270
271 // Int returns a non-negative pseudo-random int from the default Source.
272 func Int() int { return globalRand.Int() }
273
274 // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n)
275 // from the default Source.
276 // It panics if n <= 0.
277 func Int63n(n int64) int64 { return globalRand.Int63n(n) }
278
279 // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n)
280 // from the default Source.
281 // It panics if n <= 0.
282 func Int31n(n int32) int32 { return globalRand.Int31n(n) }
283
284 // Intn returns, as an int, a non-negative pseudo-random number in [0,n)
285 // from the default Source.
286 // It panics if n <= 0.
287 func Intn(n int) int { return globalRand.Intn(n) }
288
289 // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0)
290 // from the default Source.
291 func Float64() float64 { return globalRand.Float64() }
292
293 // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0)
294 // from the default Source.
295 func Float32() float32 { return globalRand.Float32() }
296
297 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n)
298 // from the default Source.
299 func Perm(n int) []int { return globalRand.Perm(n) }
300
301 // Shuffle pseudo-randomizes the order of elements using the default Source.
302 // n is the number of elements. Shuffle panics if n < 0.
303 // swap swaps the elements with indexes i and j.
304 func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }
305
306 // Read generates len(p) random bytes from the default Source and
307 // writes them into p. It always returns len(p) and a nil error.
308 // Read, unlike the Rand.Read method, is safe for concurrent use.
309 func Read(p []byte) (n int, err error) { return globalRand.Read(p) }
310
311 // NormFloat64 returns a normally distributed float64 in the range
312 // [-math.MaxFloat64, +math.MaxFloat64] with
313 // standard normal distribution (mean = 0, stddev = 1)
314 // from the default Source.
315 // To produce a different normal distribution, callers can
316 // adjust the output using:
317 //
318 // sample = NormFloat64() * desiredStdDev + desiredMean
319 func NormFloat64() float64 { return globalRand.NormFloat64() }
320
321 // ExpFloat64 returns an exponentially distributed float64 in the range
322 // (0, +math.MaxFloat64] with an exponential distribution whose rate parameter
323 // (lambda) is 1 and whose mean is 1/lambda (1) from the default Source.
324 // To produce a distribution with a different rate parameter,
325 // callers can adjust the output using:
326 //
327 // sample = ExpFloat64() / desiredRateParameter
328 func ExpFloat64() float64 { return globalRand.ExpFloat64() }
329
330 // LockedSource is an implementation of Source that is concurrency-safe.
331 // A Rand using a LockedSource is safe for concurrent use.
332 //
333 // The zero value of LockedSource is valid, but should be seeded before use.
334 type LockedSource struct {
335 lk sync.Mutex
336 src PCGSource
337 }
338
339 func (s *LockedSource) Uint64() (n uint64) {
340 s.lk.Lock()
341 n = s.src.Uint64()
342 s.lk.Unlock()
343 return
344 }
345
346 func (s *LockedSource) Seed(seed uint64) {
347 s.lk.Lock()
348 s.src.Seed(seed)
349 s.lk.Unlock()
350 }
351
352 // seedPos implements Seed for a LockedSource without a race condition.
353 func (s *LockedSource) seedPos(seed uint64, readPos *int8) {
354 s.lk.Lock()
355 s.src.Seed(seed)
356 *readPos = 0
357 s.lk.Unlock()
358 }
359
360 // Read implements Read for a LockedSource.
361 func (s *LockedSource) Read(p []byte, readVal *uint64, readPos *int8) (n int, err error) {
362 s.lk.Lock()
363 n, err = read(p, &s.src, readVal, readPos)
364 s.lk.Unlock()
365 return
366 }