Random number issue in golang

This is the code I'm working with:

package main
import "fmt"
import "math/rand"

func main() {
    code := rand.Intn(900000)
    fmt.Println(code)
}

It always prints 698081. What the is problem?

https://play.golang.org/p/XisNbqCZls

Edit:

I tried rand.Seed

package main

import "fmt"
import "time"
import "math/rand"

func main() {
    rand.Seed(time.Now().UnixNano())
    code := rand.Intn(900000)
    fmt.Println(code)
}

There is no change. Now it always prints 452000

https://play.golang.org/p/E_Wfm5tOdH

https://play.golang.org/p/aVWIN1Eb84

Upvotes: 10

Views: 4837

Answers (1)

Leo Correa
Leo Correa

Reputation: 19809

A couple of reasons why you'll see the same result in the playground

  1. Golang playground will cache the results
  2. The time in the playground always starts at the same time to make the playground deterministic.

Last but not least, the rand package default seed is 1 which will make the result deterministic. If you place a rand.Seed(time.Now().UnixNano()) you'll receive different results at each execution. Note that this won't work on the playground for the second reason above.

Upvotes: 24

Related Questions