Copyright 2009 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Package rand implements pseudo-random number generators. Random numbers are generated by a Source. Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run. The default Source, a LockedSource, is safe for concurrent use by multiple goroutines, but Sources created by NewSource are not. However, Sources are small and it is reasonable to have a separate Source for each goroutine, seeded differently, to avoid locking. For random numbers suitable for security-sensitive work, see the crypto/rand package.
package rand

import 
A Source represents a source of uniformly-distributed pseudo-random int64 values in the range [0, 1<<64).
type Source interface {
	Uint64() uint64
	Seed(seed uint64)
}
NewSource returns a new pseudo-random Source seeded with the given value.
func ( uint64) Source {
	var  PCGSource
	.Seed()
	return &
}
A Rand is a source of random numbers.
type Rand struct {
	src Source
readVal contains remainder of 64-bit integer used for bytes generation during most recent Read call. It is saved so next Read call can start where the previous one finished.
readPos indicates the number of low-order bytes of readVal that are still valid.
New returns a new Rand that uses random values from src to generate other random values.
func ( Source) *Rand {
	return &Rand{src: }
}
Seed uses the provided seed value to initialize the generator to a deterministic state. Seed should not be called concurrently with any other Rand method.
func ( *Rand) ( uint64) {
	if ,  := .src.(*LockedSource);  {
		.seedPos(, &.readPos)
		return
	}

	.src.Seed()
	.readPos = 0
}
Uint64 returns a pseudo-random 64-bit integer as a uint64.
func ( *Rand) () uint64 { return .src.Uint64() }
Int63 returns a non-negative pseudo-random 63-bit integer as an int64.
func ( *Rand) () int64 { return int64(.src.Uint64() &^ (1 << 63)) }
Uint32 returns a pseudo-random 32-bit value as a uint32.
func ( *Rand) () uint32 { return uint32(.Uint64() >> 32) }
Int31 returns a non-negative pseudo-random 31-bit integer as an int32.
func ( *Rand) () int32 { return int32(.Uint64() >> 33) }
Int returns a non-negative pseudo-random int.
func ( *Rand) () int {
	 := uint(.Uint64())
	return int( << 1 >> 1) // clear sign bit.
}

const maxUint64 = (1 << 64) - 1
Uint64n returns, as a uint64, a pseudo-random number in [0,n). It is guaranteed more uniform than taking a Source value mod n for any n that is not a power of 2.
func ( *Rand) ( uint64) uint64 {
	if &(-1) == 0 { // n is power of two, can mask
		if  == 0 {
			panic("invalid argument to Uint64n")
		}
		return .Uint64() & ( - 1)
If n does not divide v, to avoid bias we must not use a v that is within maxUint64%n of the top of the range.
	 := .Uint64()
	if  > maxUint64- { // Fast check.
		 := maxUint64 - maxUint64%
		for  >=  {
			 = .Uint64()
		}
	}

	return  % 
}
Int63n returns, as an int64, a non-negative pseudo-random number in [0,n). It panics if n <= 0.
func ( *Rand) ( int64) int64 {
	if  <= 0 {
		panic("invalid argument to Int63n")
	}
	return int64(.Uint64n(uint64()))
}
Int31n returns, as an int32, a non-negative pseudo-random number in [0,n). It panics if n <= 0.
func ( *Rand) ( int32) int32 {
	if  <= 0 {
		panic("invalid argument to Int31n")
TODO: Avoid some 64-bit ops to make it more efficient on 32-bit machines.
	return int32(.Uint64n(uint64()))
}
Intn returns, as an int, a non-negative pseudo-random number in [0,n). It panics if n <= 0.
func ( *Rand) ( int) int {
	if  <= 0 {
		panic("invalid argument to Intn")
TODO: Avoid some 64-bit ops to make it more efficient on 32-bit machines.
	return int(.Uint64n(uint64()))
}
Float64 returns, as a float64, a pseudo-random number in [0.0,1.0).
There is one bug in the value stream: r.Int63() may be so close to 1<<63 that the division rounds up to 1.0, and we've guaranteed that the result is always less than 1.0. We tried to fix this by mapping 1.0 back to 0.0, but since float64 values near 0 are much denser than near 1, mapping 1 to 0 caused a theoretically significant overshoot in the probability of returning 0. Instead of that, if we round up to 1, just try again. Getting 1 only happens 1/2⁵³ of the time, so most clients will not observe it anyway.
:
	 := float64(.Uint64n(1<<53)) / (1 << 53)
	if  == 1.0 {
		goto  // resample; this branch is taken O(never)
	}
	return 
}
Float32 returns, as a float32, a pseudo-random number in [0.0,1.0).
We do not want to return 1.0. This only happens 1/2²⁴ of the time (plus the 1/2⁵³ of the time in Float64).
:
	 := float32(.Float64())
	if  == 1 {
		goto  // resample; this branch is taken O(very rarely)
	}
	return 
}
Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n).
func ( *Rand) ( int) []int {
In the following loop, the iteration when i=0 always swaps m[0] with m[0]. A change to remove this useless iteration is to assign 1 to i in the init statement. But Perm also effects r. Making this change will affect the final state of r. So this change can't be made for compatibility reasons for Go 1.
	for  := 0;  < ; ++ {
		 := .Intn( + 1)
		[] = []
		[] = 
	}
	return 
}
Shuffle pseudo-randomizes the order of elements. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.
func ( *Rand) ( int,  func(,  int)) {
	if  < 0 {
		panic("invalid argument to Shuffle")
	}
Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle Shuffle really ought not be called with n that doesn't fit in 32 bits. Not only will it take a very long time, but with 2³¹! possible permutations, there's no way that any PRNG can have a big enough internal state to generate even a minuscule percentage of the possible permutations. Nevertheless, the right API signature accepts an int n, so handle it as best we can.
	 :=  - 1
	for ;  > 1<<31-1-1; -- {
		 := int(.Int63n(int64( + 1)))
		(, )
	}
	for ;  > 0; -- {
		 := int(.Int31n(int32( + 1)))
		(, )
	}
}
Read generates len(p) random bytes and writes them into p. It always returns len(p) and a nil error. Read should not be called concurrently with any other Rand method.
func ( *Rand) ( []byte) ( int,  error) {
	if ,  := .src.(*LockedSource);  {
		return .Read(, &.readVal, &.readPos)
	}
	return read(, .src, &.readVal, &.readPos)
}

func ( []byte,  Source,  *uint64,  *int8) ( int,  error) {
	 := *
	 := *
	,  := .(*PCGSource)
	for  = 0;  < len(); ++ {
		if  == 0 {
			if  != nil {
				 = .Uint64()
			} else {
				 = .Uint64()
			}
			 = 8
		}
		[] = byte()
		 >>= 8
		--
	}
	* = 
	* = 
	return
}
* Top-level convenience functions
Type assert that globalRand's source is a LockedSource whose src is a *rngSource.
Seed uses the provided seed value to initialize the default Source to a deterministic state. If Seed is not called, the generator behaves as if seeded by Seed(1). Seed, unlike the Rand.Seed method, is safe for concurrent use.
func ( uint64) { globalRand.Seed() }
Int63 returns a non-negative pseudo-random 63-bit integer as an int64 from the default Source.
func () int64 { return globalRand.Int63() }
Uint32 returns a pseudo-random 32-bit value as a uint32 from the default Source.
func () uint32 { return globalRand.Uint32() }
Uint64 returns a pseudo-random 64-bit value as a uint64 from the default Source.
func () uint64 { return globalRand.Uint64() }
Int31 returns a non-negative pseudo-random 31-bit integer as an int32 from the default Source.
func () int32 { return globalRand.Int31() }
Int returns a non-negative pseudo-random int from the default Source.
func () int { return globalRand.Int() }
Int63n returns, as an int64, a non-negative pseudo-random number in [0,n) from the default Source. It panics if n <= 0.
func ( int64) int64 { return globalRand.Int63n() }
Int31n returns, as an int32, a non-negative pseudo-random number in [0,n) from the default Source. It panics if n <= 0.
func ( int32) int32 { return globalRand.Int31n() }
Intn returns, as an int, a non-negative pseudo-random number in [0,n) from the default Source. It panics if n <= 0.
func ( int) int { return globalRand.Intn() }
Float64 returns, as a float64, a pseudo-random number in [0.0,1.0) from the default Source.
func () float64 { return globalRand.Float64() }
Float32 returns, as a float32, a pseudo-random number in [0.0,1.0) from the default Source.
func () float32 { return globalRand.Float32() }
Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n) from the default Source.
func ( int) []int { return globalRand.Perm() }
Shuffle pseudo-randomizes the order of elements using the default Source. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.
func ( int,  func(,  int)) { globalRand.Shuffle(, ) }
Read generates len(p) random bytes from the default Source and writes them into p. It always returns len(p) and a nil error. Read, unlike the Rand.Read method, is safe for concurrent use.
func ( []byte) ( int,  error) { return globalRand.Read() }
NormFloat64 returns a normally distributed float64 in the range [-math.MaxFloat64, +math.MaxFloat64] with standard normal distribution (mean = 0, stddev = 1) from the default Source. To produce a different normal distribution, callers can adjust the output using: sample = NormFloat64() * desiredStdDev + desiredMean
ExpFloat64 returns an exponentially distributed float64 in the range (0, +math.MaxFloat64] with an exponential distribution whose rate parameter (lambda) is 1 and whose mean is 1/lambda (1) from the default Source. To produce a distribution with a different rate parameter, callers can adjust the output using: sample = ExpFloat64() / desiredRateParameter
LockedSource is an implementation of Source that is concurrency-safe. It is just a standard Source with its operations protected by a sync.Mutex.
type LockedSource struct {
	lk  sync.Mutex
	src *PCGSource
}

func ( *LockedSource) () ( uint64) {
	.lk.Lock()
	 = .src.Uint64()
	.lk.Unlock()
	return
}

func ( *LockedSource) ( uint64) {
	.lk.Lock()
	.src.Seed()
	.lk.Unlock()
}
seedPos implements Seed for a LockedSource without a race condiiton.
func ( *LockedSource) ( uint64,  *int8) {
	.lk.Lock()
	.src.Seed()
	* = 0
	.lk.Unlock()
}
Read implements Read for a LockedSource.
func ( *LockedSource) ( []byte,  *uint64,  *int8) ( int,  error) {
	.lk.Lock()
	,  = read(, .src, , )
	.lk.Unlock()
	return