gpt4 book ai didi

ruby 精确数对数(对数)函数

转载 作者:太空宇宙 更新时间:2023-11-03 16:40:35 27 4
gpt4 key购买 nike

由于 1000 的以 10 为底的对数是 3,您可能期望 Math::log(1000, 10) 返回 3。相反,它返回 2.9999999999999996

这是因为 Ruby 中的 float 不是精确的数字,例如 here。 :

Float isn't an exact number representation, as stated in the ruby docs:

Float objects represent inexact real numbers using the native architecture's double-precision floating point representation.

这不是 ruby​​ 错误,因为 float 只能由固定的表示 字节数,因此无法正确存储十进制数。

或者,您可以使用 ruby RationalBigDecimal

遗憾的是,当调用 Math::log(BigDecimal('1000'), BigDecimal('10')) 时,结果完全一样。 Math::log(Rational('1000'), Rational('10')) 也是如此。还有一个 BigMath::log does something completely different .

现在最大的问题是:我们如何计算 1000 的以 10 为底的对数,以便我们得到准确的结果:3

最佳答案

您在这里遇到了 float 的限制。 Floats typically have a precision of 15 decimal places in Ruby ,但值 2.9999999999999996 显示 16 位小数(不可靠)精度。

为了回到可靠的精度,四舍五入到小数点后 15 位:

>> Math::log(1000, 10)
=> 2.9999999999999996
>> Math::log(1000, 10).round(15)
=> 3.0

C 语言规范 only requires 10 significant decimal places对于 double,因此 Ruby 实现可能会有少于 15 位有效小数位的 Float,但看到 15 位有效小数位仍然更为常见放在这里。

关于ruby 精确数对数(对数)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56369110/

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