Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty with Go Rand package

Tags:

go

Is there any Go function which returns true pseudo random number in every run? What I actually mean is, consider following code,

package main

import (
    "fmt"
    "rand"
)

func main() {
    fmt.Println(rand.Int31n(100))
}

Every time I execute this code, I get the same output. Is there a method that will return different, random results each time that it is called?

like image 796
Arpssss Avatar asked Nov 27 '11 20:11

Arpssss


People also ask

What is Intn go?

Intn(n) The rand. Intn() function accepts a number n and returns an unsigned pseudorandom integer in the interval [0, n) . It will throw an error if the value of n is less than zero.

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."

What is Rand Intn Golang?

The rand. Intn function returns, as an int, a non-negative pseudo-random number in [0,n) from the default source. five_random.go. package main import ( "fmt" "math/rand" "time" ) func init() { rand.Seed(time.Now().UnixNano()) } func main() { for i := 0; i < 5; i++ { fmt.Printf("%d ", rand.Intn(20)) } fmt.Println() }

What is Rand source?

A Rand is a source of random numbers.


2 Answers

The package rand can be used to generate pseudo random numbers, which are generated based on a specific initial value (called "seed").

A popular choice for this initial seed is for example the current time in nanoseconds - a value which will probably differ when you execute your program multiple times. You can initialize the random generator with the current time with something like this:

rand.Seed(time.Now().UnixNano())

(don't forget to import the time package for that)

There is also another package called crypto/rand which can be used to generate better random values (this generator might also take the user's mouse movements, the current heat of the processor and a lot of other factors into account). However, the functions in this package are several times slower and, unless you don't write a pass-phrase generator (or other security related stuff), the normal rand package is probably fine.

like image 67
tux21b Avatar answered Sep 17 '22 14:09

tux21b


You have to seed the RNG first.

I've never used Go, but it's probably rand.Seed(x);

like image 39
Tom van der Woerdt Avatar answered Sep 20 '22 14:09

Tom van der Woerdt