Golang 中给定粒度范围内的随机数

Random number within range and a given granularity in Golang

我编写了以下代码来创建一个介于 0.0 和 10.0 之间的随机数。

const minRand = 0
const maxRand = 10
v := minRand + rand.Float64()*(maxRand-minRand)

但是,我想将粒度设置为0.05,所以不允许所有数字都是最低有效小数点,只允许0和5,例如:

如何在 Go 中生成这样的数字?

你可以除以粒度,得到一个伪随机整数,然后乘以粒度以缩小结果。

const minRand = 8
const maxRand = 10
v := float64(rand.Intn((maxRand-minRand)/0.05))*0.05 + minRand
fmt.Printf("%.2f\n", v)

这将打印:

8.05
8.35
8.35
8.95
8.05
9.90
....

如果不想每次都得到相同的序列rand.Seed(time.Now().UTC().UnixNano())

From the docs

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.

有下限

const minRand = 0
const maxRand = 10
const stepRand = 0.05

v := float64(rand.Intn((maxRand-minRand)/stepRand))*stepRand + minRand
fmt.Printf("%.2f\n", v)