github.com/q45/go@v0.0.0-20151101211701-a4fb8c13db3f/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  
    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  // Read generates len(p) random bytes and writes them into p. It
   160  // always returns len(p) and a nil error.
   161  func (r *Rand) Read(p []byte) (n int, err error) {
   162  	for i := 0; i < len(p); i += 7 {
   163  		val := r.src.Int63()
   164  		for j := 0; i+j < len(p) && j < 7; j++ {
   165  			p[i+j] = byte(val)
   166  			val >>= 8
   167  		}
   168  	}
   169  	return len(p), nil
   170  }
   171  
   172  /*
   173   * Top-level convenience functions
   174   */
   175  
   176  var globalRand = New(&lockedSource{src: NewSource(1)})
   177  
   178  // Seed uses the provided seed value to initialize the default Source to a
   179  // deterministic state. If Seed is not called, the generator behaves as
   180  // if seeded by Seed(1).
   181  func Seed(seed int64) { globalRand.Seed(seed) }
   182  
   183  // Int63 returns a non-negative pseudo-random 63-bit integer as an int64
   184  // from the default Source.
   185  func Int63() int64 { return globalRand.Int63() }
   186  
   187  // Uint32 returns a pseudo-random 32-bit value as a uint32
   188  // from the default Source.
   189  func Uint32() uint32 { return globalRand.Uint32() }
   190  
   191  // Int31 returns a non-negative pseudo-random 31-bit integer as an int32
   192  // from the default Source.
   193  func Int31() int32 { return globalRand.Int31() }
   194  
   195  // Int returns a non-negative pseudo-random int from the default Source.
   196  func Int() int { return globalRand.Int() }
   197  
   198  // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n)
   199  // from the default Source.
   200  // It panics if n <= 0.
   201  func Int63n(n int64) int64 { return globalRand.Int63n(n) }
   202  
   203  // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n)
   204  // from the default Source.
   205  // It panics if n <= 0.
   206  func Int31n(n int32) int32 { return globalRand.Int31n(n) }
   207  
   208  // Intn returns, as an int, a non-negative pseudo-random number in [0,n)
   209  // from the default Source.
   210  // It panics if n <= 0.
   211  func Intn(n int) int { return globalRand.Intn(n) }
   212  
   213  // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0)
   214  // from the default Source.
   215  func Float64() float64 { return globalRand.Float64() }
   216  
   217  // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0)
   218  // from the default Source.
   219  func Float32() float32 { return globalRand.Float32() }
   220  
   221  // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n)
   222  // from the default Source.
   223  func Perm(n int) []int { return globalRand.Perm(n) }
   224  
   225  // Read generates len(p) random bytes from the default Source and
   226  // writes them into p. It always returns len(p) and a nil error.
   227  func Read(p []byte) (n int, err error) { return globalRand.Read(p) }
   228  
   229  // NormFloat64 returns a normally distributed float64 in the range
   230  // [-math.MaxFloat64, +math.MaxFloat64] with
   231  // standard normal distribution (mean = 0, stddev = 1)
   232  // from the default Source.
   233  // To produce a different normal distribution, callers can
   234  // adjust the output using:
   235  //
   236  //  sample = NormFloat64() * desiredStdDev + desiredMean
   237  //
   238  func NormFloat64() float64 { return globalRand.NormFloat64() }
   239  
   240  // ExpFloat64 returns an exponentially distributed float64 in the range
   241  // (0, +math.MaxFloat64] with an exponential distribution whose rate parameter
   242  // (lambda) is 1 and whose mean is 1/lambda (1) from the default Source.
   243  // To produce a distribution with a different rate parameter,
   244  // callers can adjust the output using:
   245  //
   246  //  sample = ExpFloat64() / desiredRateParameter
   247  //
   248  func ExpFloat64() float64 { return globalRand.ExpFloat64() }
   249  
   250  type lockedSource struct {
   251  	lk  sync.Mutex
   252  	src Source
   253  }
   254  
   255  func (r *lockedSource) Int63() (n int64) {
   256  	r.lk.Lock()
   257  	n = r.src.Int63()
   258  	r.lk.Unlock()
   259  	return
   260  }
   261  
   262  func (r *lockedSource) Seed(seed int64) {
   263  	r.lk.Lock()
   264  	r.src.Seed(seed)
   265  	r.lk.Unlock()
   266  }