github.com/euank/go@v0.0.0-20160829210321-495514729181/src/math/rand/rand.go (about) 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 // Random numbers are generated by a Source. Top-level functions, such as 8 // Float64 and Int, use a default shared Source that produces a deterministic 9 // sequence of values each time a program is run. Use the Seed function to 10 // initialize the default Source if different behavior is required for each run. 11 // The default Source is safe for concurrent use by multiple goroutines. 12 // 13 // For random numbers suitable for security-sensitive work, see the crypto/rand 14 // package. 15 package rand 16 17 import "sync" 18 19 // A Source represents a source of uniformly-distributed 20 // pseudo-random int64 values in the range [0, 1<<63). 21 type Source interface { 22 Int63() int64 23 Seed(seed int64) 24 } 25 26 // NewSource returns a new pseudo-random Source seeded with the given value. 27 func NewSource(seed int64) Source { 28 var rng rngSource 29 rng.Seed(seed) 30 return &rng 31 } 32 33 // A Rand is a source of random numbers. 34 type Rand struct { 35 src Source 36 37 // readVal contains remainder of 63-bit integer used for bytes 38 // generation during most recent Read call. 39 // It is saved so next Read call can start where the previous 40 // one finished. 41 readVal int64 42 // readPos indicates the number of low-order bytes of readVal 43 // that are still valid. 44 readPos int8 45 } 46 47 // New returns a new Rand that uses random values from src 48 // to generate other random values. 49 func New(src Source) *Rand { return &Rand{src: src} } 50 51 // Seed uses the provided seed value to initialize the generator to a deterministic state. 52 // Seed should not be called concurrently with any other Rand method. 53 func (r *Rand) Seed(seed int64) { 54 if lk, ok := r.src.(*lockedSource); ok { 55 lk.seedPos(seed, &r.readPos) 56 return 57 } 58 59 r.src.Seed(seed) 60 r.readPos = 0 61 } 62 63 // Int63 returns a non-negative pseudo-random 63-bit integer as an int64. 64 func (r *Rand) Int63() int64 { return r.src.Int63() } 65 66 // Uint32 returns a pseudo-random 32-bit value as a uint32. 67 func (r *Rand) Uint32() uint32 { return uint32(r.Int63() >> 31) } 68 69 // Int31 returns a non-negative pseudo-random 31-bit integer as an int32. 70 func (r *Rand) Int31() int32 { return int32(r.Int63() >> 32) } 71 72 // Int returns a non-negative pseudo-random int. 73 func (r *Rand) Int() int { 74 u := uint(r.Int63()) 75 return int(u << 1 >> 1) // clear sign bit if int == int32 76 } 77 78 // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n). 79 // It panics if n <= 0. 80 func (r *Rand) Int63n(n int64) int64 { 81 if n <= 0 { 82 panic("invalid argument to Int63n") 83 } 84 if n&(n-1) == 0 { // n is power of two, can mask 85 return r.Int63() & (n - 1) 86 } 87 max := int64((1 << 63) - 1 - (1<<63)%uint64(n)) 88 v := r.Int63() 89 for v > max { 90 v = r.Int63() 91 } 92 return v % n 93 } 94 95 // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n). 96 // It panics if n <= 0. 97 func (r *Rand) Int31n(n int32) int32 { 98 if n <= 0 { 99 panic("invalid argument to Int31n") 100 } 101 if n&(n-1) == 0 { // n is power of two, can mask 102 return r.Int31() & (n - 1) 103 } 104 max := int32((1 << 31) - 1 - (1<<31)%uint32(n)) 105 v := r.Int31() 106 for v > max { 107 v = r.Int31() 108 } 109 return v % n 110 } 111 112 // Intn returns, as an int, a non-negative pseudo-random number in [0,n). 113 // It panics if n <= 0. 114 func (r *Rand) Intn(n int) int { 115 if n <= 0 { 116 panic("invalid argument to Intn") 117 } 118 if n <= 1<<31-1 { 119 return int(r.Int31n(int32(n))) 120 } 121 return int(r.Int63n(int64(n))) 122 } 123 124 // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0). 125 func (r *Rand) Float64() float64 { 126 // A clearer, simpler implementation would be: 127 // return float64(r.Int63n(1<<53)) / (1<<53) 128 // However, Go 1 shipped with 129 // return float64(r.Int63()) / (1 << 63) 130 // and we want to preserve that value stream. 131 // 132 // There is one bug in the value stream: r.Int63() may be so close 133 // to 1<<63 that the division rounds up to 1.0, and we've guaranteed 134 // that the result is always less than 1.0. 135 // 136 // We tried to fix this by mapping 1.0 back to 0.0, but since float64 137 // values near 0 are much denser than near 1, mapping 1 to 0 caused 138 // a theoretically significant overshoot in the probability of returning 0. 139 // Instead of that, if we round up to 1, just try again. 140 // Getting 1 only happens 1/2⁵³ of the time, so most clients 141 // will not observe it anyway. 142 again: 143 f := float64(r.Int63()) / (1 << 63) 144 if f == 1 { 145 goto again // resample; this branch is taken O(never) 146 } 147 return f 148 } 149 150 // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0). 151 func (r *Rand) Float32() float32 { 152 // Same rationale as in Float64: we want to preserve the Go 1 value 153 // stream except we want to fix it not to return 1.0 154 // This only happens 1/2²⁴ of the time (plus the 1/2⁵³ of the time in Float64). 155 again: 156 f := float32(r.Float64()) 157 if f == 1 { 158 goto again // resample; this branch is taken O(very rarely) 159 } 160 return f 161 } 162 163 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n). 164 func (r *Rand) Perm(n int) []int { 165 m := make([]int, n) 166 // In the following loop, the iteration when i=0 always swaps m[0] with m[0]. 167 // A change to remove this useless iteration is to assign 1 to i in the init 168 // statement. But Perm also effects r. Making this change will affect 169 // the final state of r. So this change can't be made for compatibility 170 // reasons for Go 1. 171 for i := 0; i < n; i++ { 172 j := r.Intn(i + 1) 173 m[i] = m[j] 174 m[j] = i 175 } 176 return m 177 } 178 179 // Read generates len(p) random bytes and writes them into p. It 180 // always returns len(p) and a nil error. 181 // Read should not be called concurrently with any other Rand method. 182 func (r *Rand) Read(p []byte) (n int, err error) { 183 if lk, ok := r.src.(*lockedSource); ok { 184 return lk.read(p, &r.readVal, &r.readPos) 185 } 186 return read(p, r.Int63, &r.readVal, &r.readPos) 187 } 188 189 func read(p []byte, int63 func() int64, readVal *int64, readPos *int8) (n int, err error) { 190 pos := *readPos 191 val := *readVal 192 for n = 0; n < len(p); n++ { 193 if pos == 0 { 194 val = int63() 195 pos = 7 196 } 197 p[n] = byte(val) 198 val >>= 8 199 pos-- 200 } 201 *readPos = pos 202 *readVal = val 203 return 204 } 205 206 /* 207 * Top-level convenience functions 208 */ 209 210 var globalRand = New(&lockedSource{src: NewSource(1)}) 211 212 // Seed uses the provided seed value to initialize the default Source to a 213 // deterministic state. If Seed is not called, the generator behaves as 214 // if seeded by Seed(1). Seed values that have the same remainder when 215 // divided by 2^31-1 generate the same pseudo-random sequence. 216 // Seed, unlike the Rand.Seed method, is safe for concurrent use. 217 func Seed(seed int64) { globalRand.Seed(seed) } 218 219 // Int63 returns a non-negative pseudo-random 63-bit integer as an int64 220 // from the default Source. 221 func Int63() int64 { return globalRand.Int63() } 222 223 // Uint32 returns a pseudo-random 32-bit value as a uint32 224 // from the default Source. 225 func Uint32() uint32 { return globalRand.Uint32() } 226 227 // Int31 returns a non-negative pseudo-random 31-bit integer as an int32 228 // from the default Source. 229 func Int31() int32 { return globalRand.Int31() } 230 231 // Int returns a non-negative pseudo-random int from the default Source. 232 func Int() int { return globalRand.Int() } 233 234 // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n) 235 // from the default Source. 236 // It panics if n <= 0. 237 func Int63n(n int64) int64 { return globalRand.Int63n(n) } 238 239 // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n) 240 // from the default Source. 241 // It panics if n <= 0. 242 func Int31n(n int32) int32 { return globalRand.Int31n(n) } 243 244 // Intn returns, as an int, a non-negative pseudo-random number in [0,n) 245 // from the default Source. 246 // It panics if n <= 0. 247 func Intn(n int) int { return globalRand.Intn(n) } 248 249 // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0) 250 // from the default Source. 251 func Float64() float64 { return globalRand.Float64() } 252 253 // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0) 254 // from the default Source. 255 func Float32() float32 { return globalRand.Float32() } 256 257 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n) 258 // from the default Source. 259 func Perm(n int) []int { return globalRand.Perm(n) } 260 261 // Read generates len(p) random bytes from the default Source and 262 // writes them into p. It always returns len(p) and a nil error. 263 // Read, unlike the Rand.Read method, is safe for concurrent use. 264 func Read(p []byte) (n int, err error) { return globalRand.Read(p) } 265 266 // NormFloat64 returns a normally distributed float64 in the range 267 // [-math.MaxFloat64, +math.MaxFloat64] with 268 // standard normal distribution (mean = 0, stddev = 1) 269 // from the default Source. 270 // To produce a different normal distribution, callers can 271 // adjust the output using: 272 // 273 // sample = NormFloat64() * desiredStdDev + desiredMean 274 // 275 func NormFloat64() float64 { return globalRand.NormFloat64() } 276 277 // ExpFloat64 returns an exponentially distributed float64 in the range 278 // (0, +math.MaxFloat64] with an exponential distribution whose rate parameter 279 // (lambda) is 1 and whose mean is 1/lambda (1) from the default Source. 280 // To produce a distribution with a different rate parameter, 281 // callers can adjust the output using: 282 // 283 // sample = ExpFloat64() / desiredRateParameter 284 // 285 func ExpFloat64() float64 { return globalRand.ExpFloat64() } 286 287 type lockedSource struct { 288 lk sync.Mutex 289 src Source 290 } 291 292 func (r *lockedSource) Int63() (n int64) { 293 r.lk.Lock() 294 n = r.src.Int63() 295 r.lk.Unlock() 296 return 297 } 298 299 func (r *lockedSource) Seed(seed int64) { 300 r.lk.Lock() 301 r.src.Seed(seed) 302 r.lk.Unlock() 303 } 304 305 // seedPos implements Seed for a lockedSource without a race condiiton. 306 func (r *lockedSource) seedPos(seed int64, readPos *int8) { 307 r.lk.Lock() 308 r.src.Seed(seed) 309 *readPos = 0 310 r.lk.Unlock() 311 } 312 313 // read implements Read for a lockedSource without a race condition. 314 func (r *lockedSource) read(p []byte, readVal *int64, readPos *int8) (n int, err error) { 315 r.lk.Lock() 316 n, err = read(p, r.src.Int63, readVal, readPos) 317 r.lk.Unlock() 318 return 319 }