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