1

I'm trying to simulate a coin flip for a program in golang. I'm trying to use math/rand and I'm seeding it using time.

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

From what I've looked up elsewhere on here and online, my implementation should work:

func main() {
    var random int
    var i int
    var j int
    for j != 5 && i != 5 {
        rand.Seed(time.Now().UnixNano())
        random = rand.Intn(1)
        if random == 0 {
            i = i + 1
        }
        if random == 1 {
            j = j + 1
        }
    }
fmt.Println(i, j)
}

But, each time I run it, random always end up being 0. The seed doesn't change either, which confuses me. Since it's within the loop, shouldn't the time in nanoseconds change each time it's seeded?

2
  • 1
    Note also that the time doesn't change in the Go playground.
    – Vitruvie
    Mar 8, 2015 at 20:15
  • Just be aware that math/rand generates pseudo random numbers not real random numbers. (...) And these pseudo random number are vulnerable to many cryptoanalytic attacks - like what happened to PlayStation (en.wikipedia.org/wiki/Random_number_generator_attack). Mar 9, 2015 at 6:00

1 Answer 1

5

Don't reseed in the loop, do it only once.

rand.Intn(n) returns a value >= 0 and < n. So rand.Intn(1) can only return 0, you want rand.Intn(2) to get 0 or 1.

Fixed code: http://play.golang.org/p/3D9osMzRRb

2
  • Ahhhhhhhhh thanks! But why would I want to seed it just once? Wouldn't this give me the same result each time?
    – agoedken
    Mar 9, 2015 at 23:43
  • @agoedken I don't think you understand what seeding is and why it's done.
    – Dave C
    Mar 10, 2015 at 0:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.