由于 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 Rational或BigDecimal
block 引用>不幸的是,当打电话
Math::log(BigDecimal('1000'), BigDecimal('10'))
时结果是完全一样的。Math::log(Rational('1000'), Rational('10'))
也是如此。还有一个BigMath::log
其中does something completely different .现在最大的问题是:我们如何计算 1000 的以 10 为底的对数,以便得到准确的结果:
3
?
最佳答案
您在这里遇到了 float 的限制。 Float
s 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 实现的 Float
的有效小数位数可能少于 15 位,但仍然更常见的是 15 位有效小数这里的地方。
关于ruby 精确数 log(对数)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56369110/