Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number issue in golang

Tags:

random

go

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

like image 914
Özgür Yalçın Avatar asked Jul 29 '17 22:07

Özgür Yalçın


People also ask

What is math rand in GoLang?

In Golang, the rand. Seed() function is used to set a seed value to generate pseudo-random numbers. If the same seed value is used in every execution, then the same set of pseudo-random numbers is generated. In order to get a different set of pseudo-random numbers, we need to update the seed value.

How do you push random values in an array?

Use Math. random() and Math. floor() method to get the random values. Push the values one by one in the array (But this approach may generate repeated values).


1 Answers

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.

like image 151
Leo Correa Avatar answered Oct 06 '22 19:10

Leo Correa