To generate a random number in Go (actually, it’s pseudo-random, but in this article, we will refer to it as random), you just need to use the math/rand
package.
Examples
Generate random integer number (also in a given range)
package main
import (
"fmt"
"math/rand"
"time"
)
func randInt(min, max int) int {
return min + rand.Intn(max-min)
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Printf("random integer: %d\n", rand.Int())
fmt.Printf("random integer in range [5, 10): %d\n", randInt(5, 10))
}
Generate random float64 number (also in a given range)
package main
import (
"fmt"
"math/rand"
"time"
)
func randFloat(min, max float64) float64 {
return min + rand.Float64()*(max-min)
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Printf("random float64: %f\n", rand.Float64())
fmt.Printf("random float64 in range [2.4, 3.2): %f\n", randFloat(2.4, 3.2))
}
How it works
- Seed
rand.Seed(time.Now().UnixNano())
In the first line of the
main
function, we set seed to initialize a pseudorandom number generator. The defaultmath/rand
number generator is deterministic, so it will give the same output sequence for the same seed value. You can check this by removing the first line of the main function and running the program a couple of times - we always get the same “random” numbers. It is because the algorithm produces new values by performing some operations on the previous value, and when the initial value (the seed value) stays the same, we get the same output numbers. To avoid this, we use current time -time.Now().UnixNano()
as the seed. - Random number generating function
fmt.Printf("random integer: %d\n", rand.Int()) fmt.Printf("random float64: %f\n", rand.Float64())
After the seed initialization, we can generate a random number using one of the
math/rand
package functions, for example:func Int() int
func Intn(n int) int
func Int63() int64
func Int63n(n int64) int64
func Uint64() uint64
func Float64() float64
See
math/rand
package documentation for more information. - Random number in a range
func randInt(min, max int) int { return min + rand.Intn(max-min) } func randFloat(min, max float64) float64 { return min + rand.Float64()*(max-min) }
There is no function in the
math/rand
package that generates random numbers in the[min, max)
range, so we have to shift the results from the functionrand.Intn()
orrand.Float64()
to achieve a similar result. Therand.Intn()
can generate a value in the range[0, n)
, so to get a value in the range[min, max)
we need to generate a value in the range[0, max-min)
and addmin
to the result.The
rand.Float64()
produces number in[0.0, 1.0)
. To get number in[min, max)
range multiply the result bymax-min
and addmin
.