douhuo1738 2018-11-13 08:52
浏览 194
已采纳

生成均匀的随机浮点数,该浮点数可以返回所有可能的值

An easy way to generate a random float64 in [0,1) is by generating a uniformly random int in [0,2⁵³) and dividing it by 2⁵³. This is essentially what rand.Float64() is doing. However, not all possible float64 values between 0 and 1 can be generated this way: if the value is lower than 2⁻⁴ for example, the 4 last bits of the significand are always going to be 0. Or, put more simply, the naive method always returns multiples of 2⁻⁵³, and not all floating point numbers between 0 and 1 are multiples of 2⁻⁵³.

How do you generate a uniformly random float64 such as every possible value has a chance of being returned? (Here, uniformly random means over the real interval [0,1): conceptually, I want to pick a uniformly random real number between 0 and 1 and return the closest float.)

For context, I need this because I'm implementing this paper and the assumption "all possible values between 0 and 1 are represented" is essential for the result to hold.

  • 写回答

5条回答 默认 最新

  • dswqz24846 2018-11-13 17:37
    关注

    Porting this code (suggested in Severin's answer) is a possible option.

    I think that it is equivalent to first generate the significand bits (by generating a random float in [1,2)), and then choose the exponent from a geometric distribution (it has a 0.5 chance of being -1, 0.25 of being -2, etc.).

    // uniform returns a uniformly random float in [0,1).
    func uniform() float64 {
      sig := rand.Uint64() % (1 << 52)
      return (1 + float64(i)/(1<<52)) / math.Pow(2, geometric())
    }
    
    // geometric returns a number picked from a geometric
    // distribution of parameter 0.5.
    func geometric() float64 {
      b := 1
      for rand.Uint64()%2 == 0 {
         b++
      }
      return b
    }
    

    We can probably make geometric() faster by using one of the LeadingZeros* functions from the bits package instead of doing one coin flip per bit.

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

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘