10

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 returns 698081. I don't understand, 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 returns 452000

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

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

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Özgür Yalçın
  • 1,872
  • 3
  • 16
  • 26
  • 1
    Default random number generators in all programming languages, produce the same sequence with a specific seed number. Because these packages are meant to be used mainly for testing algorithms (when we need to check the result against the same input) or just as a semi-random number when used with time element. If you want a real random number, you should use the one from crypto package. – Kaveh Shahbazian Jul 30 '17 at 12:03

1 Answers1

24

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.

Leo Correa
  • 19,131
  • 2
  • 53
  • 71
  • https://play.golang.org/p/E_Wfm5tOdH - https://play.golang.org/p/aVWIN1Eb84 there is no change. now both of links always returns 452000 – Özgür Yalçın Jul 29 '17 at 22:45
  • 1
    Correct, because `time.Now()` will always return the same value in every playground to make it deterministic. Try printing that value out and you'll see why. You have to try it from your machine. – Leo Correa Jul 29 '17 at 22:54
  • Ok, i got it. The problem is resolved. Thanks for your answer. – Özgür Yalçın Jul 29 '17 at 22:59
  • Despite of using `rand.Seed(time.Now().UnixNano())` it gives the same result even if I hit "**Run**" multiple times. In the playground, it also says _"Time is constant in the playground"_ so I assume `rand.Seed(time.Now().UnixNano())` will give same value everytime. – Vishwa Dec 10 '19 at 10:03
  • Interestingly, on Google App Engine there is no problem (the random numbers are different every time) even without doing this. – Bjørn Kjos-Hanssen May 14 '20 at 00:49