Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go rand.Intn same number/value

Tags:

random

go

Can anyone please tell me why the Go example here:

https://tour.golang.org/basics/1

always returns the same value for rand.Intn(10)?

like image 970
appliedJames Avatar asked Sep 16 '16 10:09

appliedJames


People also ask

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

How to get random number in Go?

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 to generate random data in golang?

Go rand. The rand. Intn function returns, as an int, a non-negative pseudo-random number in [0,n) from the default source. The example prints five random integers. To get different pseudo random values, we seed the random generator with time.

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

2 reasons:

  1. You have to initalize the global Source used by rand.Intn() and other functions of the rand package using rand.Seed(). For example:

    rand.Seed(time.Now().UnixNano()) 

    See possible duplicate of Difficulty with Go Rand package.
    Quoting from package doc of rand:

    Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run.

  2. The Tour runs examples on the Go Playground which caches its output.
    See details at Why does count++ (instead of count = count + 1) change the way the map is returned in Golang.

like image 74
icza Avatar answered Oct 21 '22 07:10

icza