Question:
The rand package in Go provides the Int31n function to generate pseudo random numbers, but it seems to yield the same output upon repeated execution. Is there a way to obtain truly random results each time the function is called?
Answer:
The rand package employs a deterministic pseudo random number generator (PRNG). Every time the program is run, the PRNG generates the same sequence of numbers based on a fixed initial value known as the "seed."
To generate different random numbers each run, it's essential to initialize the generator with a unique seed. One common approach is to use the current time in nanoseconds, which changes every time the program is executed. This can be done using the following code:
<code class="go">import "time" func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(rand.Int31n(100)) }</code>
Alternatively, the crypto/rand package provides a more secure source of randomness. It gathers entropy from various system sources, such as mouse movements, processor temperature, and keyboard input. However, its performance may be slower compared to the rand package.
By setting a unique seed or utilizing the crypto/rand package, you can ensure that the rand.Int31n function generates truly random numbers each time it is called.
The above is the detailed content of How to Generate Truly Random Numbers with Go's Rand Package?. For more information, please follow other related articles on the PHP Chinese website!