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