加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

为什么golang重复相同的随机数?

发布时间:2020-12-16 09:27:57 所属栏目:大数据 来源:网络整理
导读:我是golang的新手,不知道为什么每次运行都会为rand.Intn(n int)int输出相同的数字: package mainimport ( "fmt" "math/rand")func main() { fmt.Println(rand.Intn(10)) } 文档说: Intn returns,as an int,a non-negative pseudo-random number in [0,n) f
我是golang的新手,不知道为什么每次运行都会为rand.Intn(n int)int输出相同的数字:

package main

import (
    "fmt"
    "math/rand"
)


func main() {
    fmt.Println(rand.Intn(10)) 
}

文档说:

Intn returns,as an int,a non-negative pseudo-random number in [0,n) from the default Source. It panics if n <= 0.

我如何正确播种随机数生成?

解决方法

通过调用 rand.Seed()函数,传递一个(随机)种子(通常是当前的unix时间戳).引自 math/rand包文档:

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.

例:

rand.Seed(time.Now().UnixNano())

如果未调用rand.Seed(),则生成器的行为就像是以1为种子:

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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读