loading...

Math/Rand in GoLang

mquanit profile image Mohammad Quanit ・1 min read

Hello, go devs I am learning golang and I am using the Math/Rand package. I am curious why I am getting the same result on:

// always returning 81
rand.Intn(100)

Does anybody have knowledge about it?

Discussion

pic
Editor guide
 

I think there's some issue with seeding. By default, it seeds some constant. I tried it on 10, 100, 1000, and 1000. It gives the same number i.e 0, 1, 81, 81 and 8081 respectively no matter how many times you repeatedly run it. Docs of golang also suggest that to avoid this behavior you should seed the rand with some value which constantly changes like time.Now().UnixNano().

 

You have to set a Seed before call Intn the first time. I think the reason for this is, the random number algorithm is deterministic. For the same Seed you get for a Intn call sequence the same random number Set. I think golang has a default Seed. Because your start random number is every time 81 for 100.

here is an example how you can set the seed by a unix timestamp.

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

Edit:

To create "real" random number for a computer is not possible.
Except perhaps when the computer is influenced by other physical processes (user input, e.g. mouse movements to generate a number) All algorithm only give the appearance of randomness. Mostly with the help of time, I think (CPU tick).
For real random numbers you can use a service like this here
random.org/

They generates randomness via atmospheric noise.

Edit2: I think it's good that the go algorithm works determistic? e.g. when you have to write a test case for code that uses random generation. You can set an own default Seed and can therefore make a prediction of the result.

 

now it makes sense to me. Thank you

 

Great replies. Also add the use of crypto/rand to generate a non deterministic random number! For an example check out - dev.to/human/to-the-point-generati...