ruby 精确数 log(对数)函数

标签 ruby logarithm

由于 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 实现的 Float 的有效小数位数可能少于 15 位,但仍然更常见的是 15 位有效小数这里的地方。

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

相关文章:

c - C中任意整数底的对数函数

c++ - 将 log10() 用于 float 时出错 -2.584877722073e-33

Ruby Hash 破坏性与非破坏性方法

ruby - 注入(inject)方法内部错误

ruby-on-rails - 在 Controller 中使用实例变量

用于匹配灰度颜色的 Ruby 正则表达式

logarithm - 使用 sqrt() 查找 log2()

algorithm - `2^n - 1` : how is it constructed? 的类 De Bruijn 序列

java - 如何在 Java 中计算以 2 为底的整数?

ruby - 无法启动瘦服务器 Ruby Gem