github.com/miolini/go@v0.0.0-20160405192216-fca68c8cb408/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.
   117  	//
   118  	// We tried to fix this by mapping 1.0 back to 0.0, but since float64
   119  	// values near 0 are much denser than near 1, mapping 1 to 0 caused
   120  	// a theoretically significant overshoot in the probability of returning 0.
   121  	// Instead of that, if we round up to 1, just try again.
   122  	// Getting 1 only happens 1/2⁵³ of the time, so most clients
   123  	// will not observe it anyway.
   124  again:
   125  	f := float64(r.Int63()) / (1 << 63)
   126  	if f == 1 {
   127  		goto again // resample; this branch is taken O(never)
   128  	}
   129  	return f
   130  }
   131  
   132  // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0).
   133  func (r *Rand) Float32() float32 {
   134  	// Same rationale as in Float64: we want to preserve the Go 1 value
   135  	// stream except we want to fix it not to return 1.0
   136  	// This only happens 1/2²⁴ of the time (plus the 1/2⁵³ of the time in Float64).
   137  again:
   138  	f := float32(r.Float64())
   139  	if f == 1 {
   140  		goto again // resample; this branch is taken O(very rarely)
   141  	}
   142  	return f
   143  }
   144  
   145  // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n).
   146  func (r *Rand) Perm(n int) []int {
   147  	m := make([]int, n)
   148  	// In the following loop, the iteration when i=0 always swaps m[0] with m[0].
   149  	// A change to remove this useless iteration is to assign 1 to i in the init
   150  	// statement. But Perm also effects r. Making this change will affect
   151  	// the final state of r. So this change can't be made for compatibility
   152  	// reasons for Go 1.
   153  	for i := 0; i < n; i++ {
   154  		j := r.Intn(i + 1)
   155  		m[i] = m[j]
   156  		m[j] = i
   157  	}
   158  	return m
   159  }
   160  
   161  // Read generates len(p) random bytes and writes them into p. It
   162  // always returns len(p) and a nil error.
   163  func (r *Rand) Read(p []byte) (n int, err error) {
   164  	for i := 0; i < len(p); i += 7 {
   165  		val := r.src.Int63()
   166  		for j := 0; i+j < len(p) && j < 7; j++ {
   167  			p[i+j] = byte(val)
   168  			val >>= 8
   169  		}
   170  	}
   171  	return len(p), nil
   172  }
   173  
   174  /*
   175   * Top-level convenience functions
   176   */
   177  
   178  var globalRand = New(&lockedSource{src: NewSource(1)})
   179  
   180  // Seed uses the provided seed value to initialize the default Source to a
   181  // deterministic state. If Seed is not called, the generator behaves as
   182  // if seeded by Seed(1).
   183  func Seed(seed int64) { globalRand.Seed(seed) }
   184  
   185  // Int63 returns a non-negative pseudo-random 63-bit integer as an int64
   186  // from the default Source.
   187  func Int63() int64 { return globalRand.Int63() }
   188  
   189  // Uint32 returns a pseudo-random 32-bit value as a uint32
   190  // from the default Source.
   191  func Uint32() uint32 { return globalRand.Uint32() }
   192  
   193  // Int31 returns a non-negative pseudo-random 31-bit integer as an int32
   194  // from the default Source.
   195  func Int31() int32 { return globalRand.Int31() }
   196  
   197  // Int returns a non-negative pseudo-random int from the default Source.
   198  func Int() int { return globalRand.Int() }
   199  
   200  // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n)
   201  // from the default Source.
   202  // It panics if n <= 0.
   203  func Int63n(n int64) int64 { return globalRand.Int63n(n) }
   204  
   205  // Int31n returns, as an int32, a non-negative pseudo-random number in [0,n)
   206  // from the default Source.
   207  // It panics if n <= 0.
   208  func Int31n(n int32) int32 { return globalRand.Int31n(n) }
   209  
   210  // Intn returns, as an int, a non-negative pseudo-random number in [0,n)
   211  // from the default Source.
   212  // It panics if n <= 0.
   213  func Intn(n int) int { return globalRand.Intn(n) }
   214  
   215  // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0)
   216  // from the default Source.
   217  func Float64() float64 { return globalRand.Float64() }
   218  
   219  // Float32 returns, as a float32, a pseudo-random number in [0.0,1.0)
   220  // from the default Source.
   221  func Float32() float32 { return globalRand.Float32() }
   222  
   223  // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n)
   224  // from the default Source.
   225  func Perm(n int) []int { return globalRand.Perm(n) }
   226  
   227  // Read generates len(p) random bytes from the default Source and
   228  // writes them into p. It always returns len(p) and a nil error.
   229  func Read(p []byte) (n int, err error) { return globalRand.Read(p) }
   230  
   231  // NormFloat64 returns a normally distributed float64 in the range
   232  // [-math.MaxFloat64, +math.MaxFloat64] with
   233  // standard normal distribution (mean = 0, stddev = 1)
   234  // from the default Source.
   235  // To produce a different normal distribution, callers can
   236  // adjust the output using:
   237  //
   238  //  sample = NormFloat64() * desiredStdDev + desiredMean
   239  //
   240  func NormFloat64() float64 { return globalRand.NormFloat64() }
   241  
   242  // ExpFloat64 returns an exponentially distributed float64 in the range
   243  // (0, +math.MaxFloat64] with an exponential distribution whose rate parameter
   244  // (lambda) is 1 and whose mean is 1/lambda (1) from the default Source.
   245  // To produce a distribution with a different rate parameter,
   246  // callers can adjust the output using:
   247  //
   248  //  sample = ExpFloat64() / desiredRateParameter
   249  //
   250  func ExpFloat64() float64 { return globalRand.ExpFloat64() }
   251  
   252  type lockedSource struct {
   253  	lk  sync.Mutex
   254  	src Source
   255  }
   256  
   257  func (r *lockedSource) Int63() (n int64) {
   258  	r.lk.Lock()
   259  	n = r.src.Int63()
   260  	r.lk.Unlock()
   261  	return
   262  }
   263  
   264  func (r *lockedSource) Seed(seed int64) {
   265  	r.lk.Lock()
   266  	r.src.Seed(seed)
   267  	r.lk.Unlock()
   268  }