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