gpt4 book ai didi

ruby - 为什么我的 BigDecimal 对象初始化时出现意外舍入错误?

转载 作者:数据小太阳 更新时间:2023-10-29 06:31:11 27 4
gpt4 key购买 nike

在 Ruby 2.2.0 中,为什么:

BigDecimal.new(34.13985572755337, 9)

等于 34.0 但是

BigDecimal.new(34.13985572755338, 9)

等于 34.1398557?

请注意,我在 64 位机器上运行它。

最佳答案

用字符串而不是 float 初始化

一般来说,您无法通过 float 获得可靠的行为。您错误地使用 Float 值而不是 String 值初始化 BigDecimals,这在一开始就引入了一些不精确性。例如,在我的 64 位系统上:

float1 = 34.13985572755337
float2 = 34.13985572755338

# You can use string literals here, too, if your Float can't be properly
# represented. For example:
#
# BigDecimal.new("34.13985572755337", 9)
#
# would be safer, but Float#to_s works fine with the provided corpus.
bd1 = BigDecimal.new(float1.to_s, 9)
bd2 = BigDecimal.new(float2.to_s, 9)

bd1.to_s
#=> "0.3413985572755337E2"
bd2.to_s
#=> "0.3413985572755338E2"

bd1.to_f == float1
#=> true
bd2.to_f == float2
#=> true

这是参数的内部表示很重要的情况之一。因此,您的里程将根据您初始化对象的方式而有所不同。

关于ruby - 为什么我的 BigDecimal 对象初始化时出现意外舍入错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28295583/

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