-
Notifications
You must be signed in to change notification settings - Fork 27
/
random.go
60 lines (50 loc) · 1.57 KB
/
random.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"fmt"
"math/rand"
"time"
)
// Go’s math/rand package provides pseudorandom number generation.
// Random function to illustrate pseudorandom number generation.
func Random() {
// For example, rand.Intn returns a random int n, 0 <= n < 100.
fmt.Print(rand.Intn(100), ",")
fmt.Print(rand.Intn(100))
fmt.Println()
// rand.Float64 returns a float64 f, 0.0 <= f < 1.0.
fmt.Println(rand.Float64())
// This can be used to generate random floats in other ranges,
// for example 5.0 <= f' < 10.0.
fmt.Print((rand.Float64()*5)+5, ",")
fmt.Print((rand.Float64() * 5) + 5)
fmt.Println()
/*
The default number generator is deterministic,
so it’ll produce the same sequence of numbers each time by default.
To produce varying sequences,
give it a seed that changes. Note that this is not safe to
use for random numbers you intend to be secret,
use crypto/rand for those.
*/
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
// Call the resulting rand.Rand just like the functions on the rand package.
fmt.Print(r1.Intn(100), ",")
fmt.Print(r1.Intn(100))
fmt.Println()
// If you seed a source with the same number,
// it produces the same sequence of random numbers.
s2 := rand.NewSource(42)
r2 := rand.New(s2)
fmt.Print(r2.Intn(100), ",")
fmt.Print(r2.Intn(100))
fmt.Println()
s3 := rand.NewSource(42)
r3 := rand.New(s3)
fmt.Print(r3.Intn(100), ",")
fmt.Print(r3.Intn(100))
fmt.Println()
// See the math/rand package
// docs for references on other random quantities that Go can provide.
// https://golang.org/pkg/math/rand/
}