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