go - 为什么每次运行程序时 math/rand 包中的 rand.Intn() 函数都会生成相同的随机数序列?

标签 go slice

我使用 rand.Intn(n int) 函数交换 slice 内的元素,但每次运行该程序时,输出都是 slice 内相同的随机元素序列。

我在这里缺少什么明显的东西?

最佳答案

来自 documentation

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

If Seed is not called, the generator behaves as if seeded by Seed(1).

默认情况下,每次运行都会获得相同的种子。

您可以使用当前时间作为种子来获得不确定性较低的序列。

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

关于go - 为什么每次运行程序时 math/rand 包中的 rand.Intn() 函数都会生成相同的随机数序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47113588/

相关文章:

go - 如何在 go-lang 中获取矩阵的维数?

memory-management - 在保持其子 slice 的同时生长 slice

go - 如何创建字节矩阵Golang

python - 如何在 python 中将 2d 列表分成两个单独的列表?

go - 使用同步/原子包进行同步的代码中的意外行为

go - 实现 io.Reader 时,无限循环中 break 与 return 的不同行为

go - 如何在 Gorm 中正确执行部分更新?

Golang 移位运算符转换

python - python range()[ :] 的切片行为

go - Reader接口(interface)改变值