Go生成随机数 - Go语言中文社区

Go生成随机数


引用自:官方文档math/rand

生成随机数首先要初始化随机种子,不然每次生成都是(指每次重新开始)相同的数,例如:

初始化随机种子函数

func Seed(seed int64)

Seed uses the provided seed value to initialize the default Source to a deterministic state. If Seed is not called, the generator behaves as if seeded by Seed(1). Seed values that have the same remainder when divided by 2^31-1 generate the same pseudo-random sequence. Seed, unlike the Rand.Seed method, is safe for concurrent use.

大概的意思是:系统每次都会先用Seed函数初始化系统资源,如果用户不提供seed参数,则默认用seed=1来初始化,这就是为什么每次都输出一样的值的原因

正确的应该是用一个不确定数来初始化随机种子,拉达到随机数随机分布的效果,unix时间就是一个很好的助手

Intn函数

func Intn(n int) int

Intn returns, as an int, a non-negative pseudo-random number in [0,n) from the default Source. It panics if n <= 0.
生成 [0,n)区间的一个随机数(注意:不包括n)

更多函数请参考官方文档

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/nail_candy/article/details/97104253
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-07 20:48:30
  • 阅读 ( 1494 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢