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.
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