gpt4 book ai didi

ruby - BigDecimal 在乘法后失去精度

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

我在 ruby​​ 中遇到 BigDecimal 的奇怪行为。为什么打印出来是假的?

require 'bigdecimal'

a = BigDecimal.new('100')
b = BigDecimal.new('5.1')
c = a / b
puts c * b == a #false

最佳答案

BigDecimal 并不声称具有无限精度,它只是提供对正常浮点范围之外的精度的支持:

BigDecimal provides similar support for very large or very accurate floating point numbers.

但是 BigDecimal 值的有效数字位数仍然有限,因此 precs method :

precs

Returns an Array of two Integer values.

The first value is the current number of significant digits in the BigDecimal. The second value is the maximum number of significant digits for the BigDecimal.

如果您查看 c,您会发现事情开始出错了:

>> c.to_s
=> "0.19607843137254901960784313725E2"

这是一个非常干净的有理数,但 BigDecimal 不知道这一点,它仍然将 c 视为有限的数字串。

如果您改用 Rational,您将获得预期的结果:

>> a = Rational(100)
>> b = Rational(51, 10)
>> c * b == a
=> true

当然,这种技巧只适用于有理数,所以任何奇特的东西(例如根或三角函数)都是越界的。

关于ruby - BigDecimal 在乘法后失去精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17003356/

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