Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random numbers over a range in Go

Tags:

random

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.

like image 211
ryboe Avatar asked May 10 '14 04:05

ryboe


People also ask

How do you generate a random number in range in Golang?

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.

How do you create a random range?

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).

Why is Intn the same number as Rand?

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."

What is math rand in Golang?

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.


1 Answers

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()) 
like image 136
ryboe Avatar answered Sep 24 '22 02:09

ryboe