gpt4 book ai didi

ruby - Ruby 2.4 中的浮点舍入更改

转载 作者:数据小太阳 更新时间:2023-10-29 07:14:07 24 4
gpt4 key购买 nike

Ruby 2.4 使用高斯舍入法对 float 进行舍入。

根据维基百科:

A tie-breaking rule that is less biased (even when the original numbers are positive or negative with unequal probability) is round half to even. By this convention, if the fraction of y is 0.5, then q is the even integer nearest to y. Thus, for example, +23.5 becomes +24, as does +24.5; while −23.5 becomes −24, as does −24.5.

但是,在 Ruby 2.4 中执行以下代码会产生与预期不同的输出。

[1.5, 2.5, 3.5, 4.5, 5.5].each { | num | puts num.round }
# output:
2
3
4
5
6
# expected output(based on Gaussian rounding):
2
2
4
4
6

有人可以解释为什么会这样或者我错过了什么吗?

最佳答案

为了应用高斯舍入,您必须传递关键字参数 :half

关键字参数 :half 可以采用 :down:even 并且默认行为仍然是向上舍入,就像它一样之前。

# ruby 2.4.0-rc1
irb(main):001:0> (2.5).round
# => 3
irb(main):008:0> (2.5).round(half: :down)
# => 2
irb(main):009:0> (2.5).round(half: :even)
# => 2

此决定的背景在 this blog post 中.

关于ruby - Ruby 2.4 中的浮点舍入更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42268878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com