"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Go语言Rand包生成真正随机数的技巧

Go语言Rand包生成真正随机数的技巧

Posted on 2025-04-14
Browse:818

How to Generate Truly Random Numbers with Go's Rand Package?

Troubleshooting Pseudo Random Number Generation in Go with the Rand Package

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:

import "time"

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(rand.Int31n(100))
}

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3