Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Random Numbers in Go

Tags:

random

go

I am trying to generate random numbers (integers) in Go, to no avail. I found the rand package in crypto/rand, which seems to be what I want, but I can't tell from the documentation how to use it. This is what I'm trying right now:

    b := []byte{}     something, err := rand.Read(b)     fmt.Printf("something = %v\n", something)     fmt.Printf("err = %v\n", err) 

But unfortunately this always outputs:

    something = 0     err = <nil> 

Is there a way to fix this so that it actually generates random numbers? Alternatively, is there a way to set the upper bound on the random numbers this generates?

like image 213
Chris Bunch Avatar asked May 30 '11 22:05

Chris Bunch


People also ask

What is math rand in Golang?

Golang provides a package math/rand for generating pseudorandom numbers. This package basically uses a single source that causes the production of a deterministic sequence of values each time a program is executed.

What is Rand seed go?

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.

Why is Intn the same number as Rand?

Intn(10)? The note on the side says why it is that way: "Note: the environment in which these programs are executed is deterministic, so each time you run the example program rand. Intn will return the same number."


Video Answer


1 Answers

Depending on your use case, another option is the math/rand package. Don't do this if you're generating numbers that need to be completely unpredictable. It can be helpful if you need to get results that are reproducible, though -- just pass in the same seed you passed in the first time.

Here's the classic "seed the generator with the current time and generate a number" program:

package main  import (     "fmt"     "math/rand"     "time" )  func main() {     rand.Seed(time.Now().Unix())     fmt.Println(rand.Int()) } 
like image 153
Evan Shaw Avatar answered Sep 29 '22 20:09

Evan Shaw