x
1
// Go's `math/rand` package provides
2
// [pseudorandom number](http://en.wikipedia.org/wiki/Pseudorandom_number_generator)
3
// generation.
4
5
package main
6
7
import "fmt"
8
import "math/rand"
9
10
func main() {
11
12
// For example, `rand.Intn` returns a random `int` n,
13
// `0 <= n < 100`.
14
fmt.Print(rand.Intn(100), ",")
15
fmt.Print(rand.Intn(100))
16
fmt.Println()
17
18
// `rand.Float64` returns a `float64` `f`,
19
// `0.0 <= f < 1.0`.
20
fmt.Println(rand.Float64())
21
22
// This can be used to generate random floats in
23
// other ranges, for example `5.0 <= f' < 10.0`.
24
fmt.Print((rand.Float64()*5)+5, ",")
25
fmt.Print((rand.Float64() * 5) + 5)
26
fmt.Println()
27
28
// To make the pseudorandom generator deterministic,
29
// give it a well-known seed.
30
s1 := rand.NewSource(42)
31
r1 := rand.New(s1)
32
33
// Call the resulting `rand.Rand` just like the
34
// functions on the `rand` package.
35
fmt.Print(r1.Intn(100), ",")
36
fmt.Print(r1.Intn(100))
37
fmt.Println()
38
39
// If you seed a source with the same number, it
40
// produces the same sequence of random numbers.
41
s2 := rand.NewSource(42)
42
r2 := rand.New(s2)
43
fmt.Print(r2.Intn(100), ",")
44
fmt.Print(r2.Intn(100))
45
fmt.Println()
46
}
47