Why Does `rand.Intn()` in Go Generate the Same Number Every Time?

Susan Sarandon
Release: 2024-10-30 13:25:02
Original
541 people have browsed it

Why Does `rand.Intn()` in Go Generate the Same Number Every Time?

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!