Home > Backend Development > Golang > Why Do Random Numbers Repeat in Go and How Can We Fix it?

Why Do Random Numbers Repeat in Go and How Can We Fix it?

Linda Hamilton
Release: 2024-10-25 09:14:02
Original
1004 people have browsed it

Why Do Random Numbers Repeat in Go and How Can We Fix it?

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>
Copy after login

For instance, instead of:

<code class="go">package main

import (
    "fmt"
    "math/rand"
)


func main() {
    fmt.Println(rand.Intn(10)) 
}</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template