First thanks to anybody that spends the time to read this.
I’m new to Go and just found two rand packages, and got fascinated by the differences.
This discussion is extremely enlightening, but for those of you who are new to Go, like me, it might be interesting to really see the randomness of the random number generators in action.
I wrote a similar program where a generator generates random numbers between 1 and 6 and so simulates a dice roll.
Two of these generators are launched concurrently and then a collector goroutine adds up the tally of each of the generators.
This example uses math/rand:
And this example uses crypto/rand:
The first example has maybe 2 possible outcomes across all 10 rolls, usually just 1!
The second is more in line with what I’d expect from dice rolls. Sometimes A wins, sometimes B wins.
So, what I learned is: Whenever I want numbers to be random, for any games e.g., I need to use crypto/rand.
Am I getting this wrong?
Any comments on the code also greatly welcome.
You didn’t notice that you can change Seed for math/rand package for generating different sequence of number. Also as generator source.
Rand from math package use some known algorithm for generating pseudo-random numbers while rand from crypto use real random when it possible. But it costs much more.
From my point of view math/rand package can be used for simple games, but not when expected truly randomness.
The official ioutil.TempFile function (see https://golang.org/src/io/ioutil/tempfile.go) which creates temporary files with random names uses easy Numerical Recipes and seeds with time.Now().UnixNano() + int64(os.Getpid()).
It is, in the playground the time is fixed as explained here:
In the playground the time begins at 2009-11-10 23:00:00 UTC (determining the significance of this date is an exercise for the reader). This makes it easier to cache programs by giving them deterministic output.