简体   繁体   English

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

[英]Random number within range and a given granularity in Golang

I've written the following code to create a random number between 0.0 and 10.0. 我编写了以下代码来创建0.0到10.0之间的随机数。

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

However, I would like to set the granularity to 0.05, so having all the digits as the least significant decimal should not be allowed, only 0 and 5 should be allowed, eg: 但是,我想将粒度设置为0.05,因此不应将所有数字都设为最低有效十进制,而应仅允许0和5,例如:

  • the value 7.73 is NOT VALID, 值7.73无效,
  • the values 7.7 and 7.75 ARE VALID. 值7.7和7.75有效。

How can I produce such numbers in Go? 如何在Go中产生这样的数字?

You can divide with the granularity, get a pseudo random integer and then multiply with the granularity to scale the result down. 您可以除以粒度,获得伪随机整数,然后乘以粒度以缩小结果。

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

This will print: 这将打印:

8.05
8.35
8.35
8.95
8.05
9.90
....

If you don't want to get the same sequence every time rand.Seed(time.Now().UTC().UnixNano()) . 如果您不想每次都获得相同的序列rand.Seed(time.Now().UTC().UnixNano())

From the docs 来自文档

Seed uses the provided seed value to initialize the default Source to a deterministic state. Seed使用提供的种子值将默认Source初始化为确定性状态。 If Seed is not called, the generator behaves as if seeded by Seed(1). 如果未调用Seed,则生成器的行为就像由Seed(1)设置种子一样。 Seed values that have the same remainder when divided by 2^31-1 generate the same pseudo-random sequence. 除以2 ^ 31-1时具有相同余数的种子值会生成相同的伪随机序列。 Seed, unlike the Rand.Seed method, is safe for concurrent use. 与Rand.Seed方法不同,种子可以安全地同时使用。

With lower bounds 下界

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM