Understanding Identical Random Number Generation in Go's rand.Intn()
Why does rand.Intn() consistently generate the same random number? This question often arises for beginners using Go due to the following code:
<code class="go">package main import ( "fmt" "math/rand" ) func main() { fmt.Println(rand.Intn(10)) }</code>
Despite the documentation claiming to provide a pseudo-random number in the range [0, n), the program prints the same number every time.
Seeding the Random Number Generation
The key lies in properly seeding the random number generator. The default behavior is to use a deterministic seed, resulting in the same sequence of numbers across program executions. To rectify this:
<code class="go">rand.Seed(time.Now().UnixNano())</code>
This function initializes the random number generator with a seed based on the current Unix timestamp. It ensures a different sequence of numbers for each run.
Understanding the Documentation
The documentation for rand.Intn() states: "Top-level functions ... produce a deterministic sequence of values each time a program is run." Therefore, without explicit seeding, the generator acts as if seeded by 1, leading to predictable results.
Conclusion
By seeding the random number generator before using rand.Intn(), you can overcome the issue of repeating random numbers, ensuring proper generation of non-deterministic sequences.
The above is the detailed content of Why Does `rand.Intn()` in Go Generate the Same Number Every Time?. For more information, please follow other related articles on the PHP Chinese website!