19

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?

tux21b
  • 90,183
  • 16
  • 117
  • 101
Arpssss
  • 3,850
  • 6
  • 36
  • 80

3 Answers3

27

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.

serbaut
  • 5,852
  • 2
  • 28
  • 32
tux21b
  • 90,183
  • 16
  • 117
  • 101
2

You have to seed the RNG first.

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

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
  • You mean this, package main import "fmt" import "rand" func main() { rand.Seed(100); fmt.Println(rand.Int31n(100)) }. It is also giving same output all the run. – Arpssss Nov 27 '11 at 20:22
  • That's because you are seeding it with the static number 100 :-) Try using something more unique, such as the current time in milliseconds. – Tom van der Woerdt Nov 27 '11 at 20:24
0

rand.Seed(time.Now().UnixNano()) works on Ubuntu. I spent forever researching rand.Seed(time.Nanoseconds()). I finally found the Example: Google Search 2.1 on the golang tour.

fancyPants
  • 50,732
  • 33
  • 89
  • 96