HomeSearch | ## Golang rand, crypto: Random Number GeneratorsUse the rand package and generate random numbers. Call rand.Int and Seed. | |

## Rand.Everything, even the color of the grass, may be deterministic in this world. But many events seem random. We use "math/rand" in Go to simulate this effect. | ||

## With rand.Intwe get random integers. And with rand.Seed we initialize the pseudo-random number generator that the Go language uses. | ||

## An intro program.This program generates 5 pseudo-random numbers. It uses a default seed value (which initializes the generator) of 1.
| Golang program that uses rand.Int
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)
}
}
Output
5577006791947779410
8674665223082153551
6129484611666145821
4037200794235010051
3916589616287113937 | |

## Seed.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.
| Golang program that uses Seed
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)
}
Output
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.
| Golang program that uses rand.Perm
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)
}
}
Output
[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] | |

## Crypto rand.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.
| Golang program that uses crypto rand
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)
}
}
Output
54
77
56
21
56
81
55
16
57
88
95
58
12
74
23
35
72
29
25
68 | |

## Some research.Here is some research on Seed. If we do not use Seed each program execution will yield the same numbers. So we should seed with time or another source of randomness.
| ||

## Global versus local.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. | ||

Home Dot Net Perls | © 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com. |