Home | History | Annotate | Download | only in rand
      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 
     38 // New returns a new Rand that uses random values from src
     39 // to generate other random values.
     40 func New(src Source) *Rand { return &Rand{src} }
     41 
     42 // Seed uses the provided seed value to initialize the generator to a deterministic state.
     43 func (r *Rand) Seed(seed int64) { r.src.Seed(seed) }
     44 
     45 // Int63 returns a non-negative pseudo-random 63-bit integer as an int64.
     46 func (r *Rand) Int63() int64 { return r.src.Int63() }
     47 
     48 // Uint32 returns a pseudo-random 32-bit value as a uint32.
     49 func (r *Rand) Uint32() uint32 { return uint32(r.Int63() >> 31) }
     50 
     51 // Int31 returns a non-negative pseudo-random 31-bit integer as an int32.
     52 func (r *Rand) Int31() int32 { return int32(r.Int63() >> 32) }
     53 
     54 // Int returns a non-negative pseudo-random int.
     55 func (r *Rand) Int() int {
     56 	u := uint(r.Int63())
     57 	return int(u << 1 >> 1) // clear sign bit if int == int32
     58 }
     59 
     60 // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n).
     61 // It panics if n <= 0.
     62 func (r *Rand) Int63n(n int64) int64 {
     63 	if n <= 0 {
     64 		panic("invalid argument to Int63n")
     65 	}
     66 	if n&(n-1) == 0 { // n is power of two, can mask
     67 		return r.Int63() & (n - 1)
     68 	}
     69 	max := int64((1 << 63) - 1 - (1<<63)%uint64(n))
     70 	v := r.Int63()
     71 	for v > max {
     72 		v = r.Int63()
     73 	}
     74 	return v % n
     75 }
     76 
     77 // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n).
     78 // It panics if n <= 0.
     79 func (r *Rand) Int31n(n int32) int32 {
     80 	if n <= 0 {
     81 		panic("invalid argument to Int31n")
     82 	}
     83 	if n&(n-1) == 0 { // n is power of two, can mask
     84 		return r.Int31() & (n - 1)
     85 	}
     86 	max := int32((1 << 31) - 1 - (1<<31)%uint32(n))
     87 	v := r.Int31()
     88 	for v > max {
     89 		v = r.Int31()
     90 	}
     91 	return v % n
     92 }
     93 
     94 // Intn returns, as an int, a non-negative pseudo-random number in [0,n).
     95 // It panics if n <= 0.
     96 func (r *Rand) Intn(n int) int {
     97 	if n <= 0 {
     98 		panic("invalid argument to Intn")
     99 	}
    100 	if n <= 1<<31-1 {
    101 		return int(r.Int31n(int32(n)))
    102 	}
    103 	return int(r.Int63n(int64(n)))
    104 }
    105 
    106 // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0).
    107 func (r *Rand) Float64() float64 {
    108 	// A clearer, simpler implementation would be:
    109 	//	return float64(r.Int63n(1<<53)) / (1<<53)
    110 	// However, Go 1 shipped with
    111 	//	return float64(r.Int63()) / (1 << 63)
    112 	// and we want to preserve that value stream.
    113 	//
    114 	// There is one bug in the value stream: r.Int63() may be so close
    115 	// to 1<<63 that the division rounds up to 1.0, and we've guaranteed
    116 	// that the result is always less than 1.0. To fix that, we treat the
    117 	// range as cyclic and map 1 back to 0. This is justified by observing
    118 	// that while some of the values rounded down to 0, nothing was
    119 	// rounding up to 0, so 0 was underrepresented in the results.
    120 	// Mapping 1 back to zero restores some balance.
    121 	// (The balance is not perfect because the implementation
    122 	// returns denormalized numbers for very small r.Int63(),
    123 	// and those steal from what would normally be 0 results.)
    124 	// The remapping only happens 1/2 of the time, so most clients
    125 	// will not observe it anyway.
    126 	f := float64(r.Int63()) / (1 << 63)
    127 	if f == 1 {
    128 		f = 0
    129 	}
    130 	return f
    131 }
    132 
    133 // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0).
    134 func (r *Rand) Float32() float32 {
    135 	// Same rationale as in Float64: we want to preserve the Go 1 value
    136 	// stream except we want to fix it not to return 1.0
    137 	// There is a double rounding going on here, but the argument for
    138 	// mapping 1 to 0 still applies: 0 was underrepresented before,
    139 	// so mapping 1 to 0 doesn't cause too many 0s.
    140 	// This only happens 1/2 of the time (plus the 1/2 of the time in Float64).
    141 	f := float32(r.Float64())
    142 	if f == 1 {
    143 		f = 0
    144 	}
    145 	return f
    146 }
    147 
    148 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n).
    149 func (r *Rand) Perm(n int) []int {
    150 	m := make([]int, n)
    151 	for i := 0; i < n; i++ {
    152 		j := r.Intn(i + 1)
    153 		m[i] = m[j]
    154 		m[j] = i
    155 	}
    156 	return m
    157 }
    158 
    159 /*
    160  * Top-level convenience functions
    161  */
    162 
    163 var globalRand = New(&lockedSource{src: NewSource(1)})
    164 
    165 // Seed uses the provided seed value to initialize the default Source to a
    166 // deterministic state. If Seed is not called, the generator behaves as
    167 // if seeded by Seed(1).
    168 func Seed(seed int64) { globalRand.Seed(seed) }
    169 
    170 // Int63 returns a non-negative pseudo-random 63-bit integer as an int64
    171 // from the default Source.
    172 func Int63() int64 { return globalRand.Int63() }
    173 
    174 // Uint32 returns a pseudo-random 32-bit value as a uint32
    175 // from the default Source.
    176 func Uint32() uint32 { return globalRand.Uint32() }
    177 
    178 // Int31 returns a non-negative pseudo-random 31-bit integer as an int32
    179 // from the default Source.
    180 func Int31() int32 { return globalRand.Int31() }
    181 
    182 // Int returns a non-negative pseudo-random int from the default Source.
    183 func Int() int { return globalRand.Int() }
    184 
    185 // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n)
    186 // from the default Source.
    187 // It panics if n <= 0.
    188 func Int63n(n int64) int64 { return globalRand.Int63n(n) }
    189 
    190 // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n)
    191 // from the default Source.
    192 // It panics if n <= 0.
    193 func Int31n(n int32) int32 { return globalRand.Int31n(n) }
    194 
    195 // Intn returns, as an int, a non-negative pseudo-random number in [0,n)
    196 // from the default Source.
    197 // It panics if n <= 0.
    198 func Intn(n int) int { return globalRand.Intn(n) }
    199 
    200 // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0)
    201 // from the default Source.
    202 func Float64() float64 { return globalRand.Float64() }
    203 
    204 // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0)
    205 // from the default Source.
    206 func Float32() float32 { return globalRand.Float32() }
    207 
    208 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n)
    209 // from the default Source.
    210 func Perm(n int) []int { return globalRand.Perm(n) }
    211 
    212 // NormFloat64 returns a normally distributed float64 in the range
    213 // [-math.MaxFloat64, +math.MaxFloat64] with
    214 // standard normal distribution (mean = 0, stddev = 1)
    215 // from the default Source.
    216 // To produce a different normal distribution, callers can
    217 // adjust the output using:
    218 //
    219 //  sample = NormFloat64() * desiredStdDev + desiredMean
    220 //
    221 func NormFloat64() float64 { return globalRand.NormFloat64() }
    222 
    223 // ExpFloat64 returns an exponentially distributed float64 in the range
    224 // (0, +math.MaxFloat64] with an exponential distribution whose rate parameter
    225 // (lambda) is 1 and whose mean is 1/lambda (1) from the default Source.
    226 // To produce a distribution with a different rate parameter,
    227 // callers can adjust the output using:
    228 //
    229 //  sample = ExpFloat64() / desiredRateParameter
    230 //
    231 func ExpFloat64() float64 { return globalRand.ExpFloat64() }
    232 
    233 type lockedSource struct {
    234 	lk  sync.Mutex
    235 	src Source
    236 }
    237 
    238 func (r *lockedSource) Int63() (n int64) {
    239 	r.lk.Lock()
    240 	n = r.src.Int63()
    241 	r.lk.Unlock()
    242 	return
    243 }
    244 
    245 func (r *lockedSource) Seed(seed int64) {
    246 	r.lk.Lock()
    247 	r.src.Seed(seed)
    248 	r.lk.Unlock()
    249 }
    250