duanhai7274 2019-06-10 14:27
浏览 316
已采纳

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

I've written the following code to create a random number between 0.0 and 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, e.g.:

  • the value 7.73 is NOT VALID,
  • the values 7.7 and 7.75 ARE VALID.

How can I produce such numbers in Go?

  • 写回答

2条回答 默认 最新

  • dsiimyoc804955 2019-06-10 15:01
    关注

    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
    ", 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()).

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。