Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to call rand.Seed manually?

Tags:

random

go

I want to know do we have to call rand.Seed(n) manually in Go?
I have a code that looks like this:

import (
    "fmt"
    "math/rand"
)

func main() {
    fmt.Println(rand.Intn(100))
    fmt.Println(rand.Intn(100))
    fmt.Println(rand.Intn(100))
}

Everytime I run this code, each line prints different numbers than the others.
So do I need to call rand.Seed(n) each time before calling rand.Intn(100)?

like image 525
Mojtaba Arezoomand Avatar asked Sep 20 '25 12:09

Mojtaba Arezoomand


2 Answers

Prior to Go 1.20, the global, shared Source was seeded to 1 internally, so each run of the appliation would produce the same pseudo-random sequences.

Calling rand.Seed() is not needed starting from Go 1.20. Release notes:

The math/rand package now automatically seeds the global random number generator (used by top-level functions like Float64 and Int) with a random value, and the top-level Seed function has been deprecated. Programs that need a reproducible sequence of random numbers should prefer to allocate their own random source, using rand.New(rand.NewSource(seed)).

Programs that need the earlier consistent global seeding behavior can set GODEBUG=randautoseed=0 in their environment.

The top-level Read function has been deprecated. In almost all cases, crypto/rand.Read is more appropriate.

rand.Seed() also has this DEPRICATION in its doc:

Deprecated: Programs that call Seed and then expect a specific sequence of results from the global random source (using functions such as Int) can be broken when a dependency changes how much it consumes from the global random source. To avoid such breakages, programs that need a specific result sequence should use NewRand(NewSource(seed)) to obtain a random generator that other packages cannot access.

like image 145
icza Avatar answered Sep 22 '25 06:09

icza


You have to create a Source:

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    wdRand := rand.New(rand.NewSource(42))
    fmt.Println(wdRand.Intn(100))
    fmt.Println(wdRand.Intn(100))
    fmt.Println(wdRand.Intn(100))
}

https://go.dev/play/p/Sp0Wfx0Bkbb

Now everytime you call the code, the results become identical.

like image 30
h0ch5tr4355 Avatar answered Sep 22 '25 05:09

h0ch5tr4355