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.
Golang has built-in support for random number generation in the standard library. Specifically there is the math/rand package which implements pseudo-random number generators. Intn returns, as an int, a non-negative pseudo-random number in [0,n) from the default Source.
Use randrnage() to generate random integer within a range Use a random. randrange() function to get a random integer number from the given exclusive range by specifying the increment. For example, random. randrange(0, 10, 2) will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).
Intn(10)? The note on the side says why it is that way: "Note: the environment in which these programs are executed is deterministic, so each time you run the example program rand. Intn will return the same number."
Golang provides a package math/rand for generating pseudorandom numbers. This package basically uses a single source that causes the production of a deterministic sequence of values each time a program is executed.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With