加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby 2.4中的Float Rounding更改

发布时间:2020-12-17 03:29:42 所属栏目:百科 来源:网络整理
导读:Ruby 2.4使用高斯舍入来舍入浮点数. 根据维基百科: 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
Ruby 2.4使用高斯舍入来舍入浮点数.

根据维基百科:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读