mardi 11 septembre 2018

Golang generating identical random numbers in sequence after time seed? (Running on my machine)

I'm trying to understand precisely why, when called from an external function, my time seeded random number generator returns sequences of identical numbers.

Minimal working example of issue:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

//Generates random int as function of range
func getRand(Range int) int {
    s1 := rand.NewSource(time.Now().UnixNano())
    r1 := rand.New(s1)
    return r1.Intn(Range)
}

//Print 100 random ints between 0 and 100
func main() {
    for i := 0; i < 100; i++ {
        fmt.Print(getRand(100), ", ")
    }
}

The output of this is

Out[1]: 40, 40, 40, 40, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 34,
34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 47, 
47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 
47,47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 99, 99, 99, 99, 99, 99, 99, 
99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99,

I'd like to know why this is happening for my own education. I'm also open to suggestions for a solution.

Details: I need to call random numbers in lots of external functions of my code but, like this MWE, when seeded within a function other than main they repeatedly return the same numbers. Additionally, I need to dynamically update the range, so generating lists a priori is not an option. I would rather not have to generate the numbers in main() and pass them into each function-- ranges are calculated inside these and it would complicate things




Aucun commentaire:

Enregistrer un commentaire