GOLANG随机数生成方法
golang生成随机数可以使用math/rand包。
Package randPackage 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)来设置一个不同的种子值。
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 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("%dn", <-rand_service_handler) }运行:
C:/go/bin/go.exe run lx.go [E:/project/go/lx/src] 77 成功: 进程退出代码 0. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |