Rand
In Go programs we get random integers by calling rand.Int
. And with rand.Seed
we initialize the pseudo-random number generator that the Go language uses.
Rand
notesWe use "math/rand" in Go to access important random functions. We can continually call rand.Int
to get a random sequence.
This program generates 5 pseudo-random numbers. It uses a default seed value (which initializes the generator) of 1.
int
. No fractional or negative values are possible.rand.Int
, use the Seed method.package main import ( "fmt" "math/rand" ) func main() { // Loop five times. for i := 0; i < 5; i++ { // Get random positive integer. value := rand.Int() fmt.Println(value) } }5577006791947779410 8674665223082153551 6129484611666145821 4037200794235010051 3916589616287113937
This method initializes the random source. When we use a seed based on the current time, each program execution will start with a different random sequence.
int64
to seed the number generator.package main import ( "fmt" "math/rand" "time" ) func main() { // Call Seed, using current nanoseconds. rand.Seed(int64(time.Now().Nanosecond())) // Random int will be different each program execution. value := rand.Int() fmt.Println(value) }6912970929678809162
Rand.Perm
This function is useful. It generates slices of Ints with values from 0 to the max index of the slice. Each value appears only once. So it creates permutations of Ints.
rand.Perm
with an argument of 5. So the numbers 0, 1, 2, 3, and 4 are randomly arranged in slices of 5 elements.package main import ( "fmt" "math/rand" ) func main() { for i := 0; i < 5; i++ { // Use rand.Perm to generate a random array of numbers. numbers := rand.Perm(5) fmt.Println(numbers) } }[0 4 2 3 1] [4 1 2 0 3] [2 3 0 4 1] [0 4 2 1 3] [1 0 4 2 3]
Random
numbers come in varying levels of randomness. For the best random numbers built into Go, we should use crypto rand. We must use the "math/big" package.
rand.Int
method in "crypto/rand" 20 times. We get values that are from 0 to 99 inclusive (we never get 100).package main import ( "crypto/rand" "math/big" "fmt" ) func main() { // Generate 20 random numbers with exclusive max of 100. // ... So max value returned is 99. // All values returned are 0 or greater as well. for i := 0; i < 20; i++ { result, _ := rand.Int(rand.Reader, big.NewInt(100)) fmt.Println(result) } }54 77 56 21 56 81 55 16 57 88 95 58 12 74 23 35 72 29 25 68
With top-level rand methods, we use a global source. But we can create Rand
instances that are local. This helps with many randomness requirements.