GOLANG随机数生成方法

来源:互联网 发布:qq音乐 mac 版权破解 编辑:程序博客网 时间:2024/06/08 00:13

golang生成随机数可以使用math/rand包。

Package rand

import "math/rand"
Package rand implements pseudo-random number generators.

Random numbers are generated by a Source. 

Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic(固定的) sequence of values each time a program is run. 

Use the Seed function to initialize the default Source if different behavior is required for each run. 

The default Source is safe for concurrent use by multiple goroutines.


e.g.初步使用rand包

package main
import (
    "fmt"
    "math/rand"
)
func main() {
    for i := 0; i < 10; i++ {
        fmt.Println(rand.Intn(100)) //返回[0,100)的随机整数
    }
}
运行:

C:/go/bin/go.exe run lx.go [E:/project/go/lx/src]

81

87

47

59

81

18

25

40

56

0

成功: 进程退出代码 0.

这样使用是可以产生随机数,但是程序重启后,产生的随机数和上次一样。是因为程序使用了相同的种子 1。可以使用rand.Seed(seed)来设置一个不同的种子值。


e.g. 使用不同的种子初始化rand包

package main
import (
    "fmt"
    "math/rand"
    "time"
)
func main() {
    rand.Seed(time.Now().UnixNano()) //利用当前时间的UNIX时间戳初始化rand包
    for i := 0; i < 10; i++ {
        x := rand.Intn(100)
        fmt.Println(x)
    }
}
运行:

C:/go/bin/go.exe run lx2.go [E:/project/go/lx/src]

38

94

64

7

0

42

47

90

94

5

成功: 进程退出代码 0.

OK,上面的程序每次运行产生的随机数都不一样。

e.g. 将产生随机数作为一个服务

package main
import (
    "fmt"
    "math/rand"
    "time"
)
func rand_generator(n int) chan int {
    rand.Seed(time.Now().UnixNano())
    out := make(chan int)
    go func(x int) {
        for {
            out <- rand.Intn(x)
        }
    }(n)
    return out
}
func main() {
    // 生成随机数作为一个服务
    rand_service_handler := rand_generator(100)
    // 从服务中读取随机数并打印
    fmt.Printf("%d\n", <-rand_service_handler)
}
运行:

C:/go/bin/go.exe run lx.go [E:/project/go/lx/src]

77

成功: 进程退出代码 0.