Generating random numbers over a range in Go
All the integer functions in math/rand
generate non-negative numbers.
rand.Int() int // [0, MaxInt]
rand.Int31() int32 // [0, MaxInt32]
rand.Int31n(n int32) int32 // [0, n)
rand.Int63() int64 // [0, MaxInt64]
rand.Int63n(n int64) int64 // [0, n)
rand.Intn(n int) int // [0, n)
I would like to generate random numbers in the range [-m, n). In other words, I would like to generate a mix of positive and negative numbers.
I found this example at Go Cookbook, which is equivalent to rand.Range(min, max int)
(if that function existed):
rand.Intn(max - min) + min
Don't forget to seed the PRNG before calling any rand
function.
rand.Seed(time.Now().UnixNano())
This will generate random numbers within given range [a, b]
rand.Seed(time.Now().UnixNano())
n := a + rand.Intn(b-a+1)
source