Addressing Random Number Repetition in Go
In Go, random number generation can sometimes result in unexpected repetition, particularly when using rand.Intn(n int) int for generating random integers. This is attributed to the fact that the default source used by top-level random number functions, such as rand.Intn, produces a deterministic sequence of values when a program is run consecutively.
To resolve this issue, the solution lies in seeding the random number generator using the rand.Seed() function. Seeding provides the generator with a random value that serves as an initialization parameter. A common practice is to use the current Unix timestamp as the seed:
<code class="go">rand.Seed(time.Now().UnixNano())</code>
For instance, instead of:
<code class="go">package main import ( "fmt" "math/rand" ) func main() { fmt.Println(rand.Intn(10)) }</code>
Which will always return the same random number, seeding the generator will ensure a different random number for each run:
<code class="go">package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(rand.Intn(10)) }</code>
Remember that without calling rand.Seed(), the generator behaves as if seeded by the value 1, leading to the repetition of random numbers.
The above is the detailed content of Why Do Random Numbers Repeat in Go and How Can We Fix it?. For more information, please follow other related articles on the PHP Chinese website!