首页 文章

当小数分量为0.5时,Ruby方法用于随机舍入浮点数

提问于
浏览
0

我正在研究统计问题,如果小数分量为0.5,则需要随机向上或向下舍入 . 以下代码应该有效

def round_random(x)
    return x.round unless x.modulo(1) == 0.5
    x.floor + rand(2)
end

但我记得有一些关于在红宝石中做这个的讨论,所以我想知道是否实际上有一个标准的方法 .

1 回答

  • 5

    从Ruby 2.4开始,round采用可选的关键字参数 half 来指定"[...] numbers that are half-way between two possible rounded values"的循环模式

    你的方法将成为:

    def round_random(x)
      x.round(half: [:up, :down].sample)
    end
    
    round_random(2.6) #=> 3 (always)
    
    round_random(2.5) #=> 2
    round_random(2.5) #=> 3
    round_random(2.5) #=> 2
    
    round_random(2.4) #=> 2 (always)
    

    还有 :even 实现round half to even - 一个规则,以避免在出现平局的情况下舍入到下一个偶数的偏差:

    1.5.round(half: :even) #=> 2
    2.5.round(half: :even) #=> 2
    3.5.round(half: :even) #=> 4
    4.5.round(half: :even) #=> 4
    

    也许这对你的问题来说是一个更确定的替代方案 .

相关问题