是否在Ruby中的BigDecimal中使用String或Integer

时间:2022-10-11 23:26:00

Referring to the documentation of BigDecimal class,

参考BigDecimal类的文档,

n,m = a.precs
prec returns number of significant digits (n) and maximum number of significant digits (m) of a.

n,m = a.precs prec返回有效位数(n)和最大有效位数(m)。

I am puzzled by the following output related to BigDecimal.

我对以下与BigDecimal相关的输出感到困惑。

require 'bigdecimal'    
BigDecimal.new('1').precs # => [9, 18] 
BigDecimal.new(1).precs   # => [9, 27]

I cannot figure out why when a String is passed, the maximum number of significant digits is less compared to when a Fixnum is passed.

我无法弄清楚为什么在传递String时,与传递Fixnum时相比,最大有效位数会更少。

Also will it result in any precision issues?

它还会导致任何精度问题吗?

1 个解决方案

#1


3  

If you can read C code, you can start at https://github.com/ruby/ruby/blob/trunk/ext/bigdecimal/bigdecimal.c#L2509 - that's the initializer for any BigDecimal object. If you follow that code to the next method, which is BigDecimal_new you'll notice that when passed an integer argument there are a few more steps to go through before allocating and creating an internal big decimal object as opposed to when passing a string argument.

如果您可以阅读C代码,可以从https://github.com/ruby/ruby/blob/trunk/ext/bigdecimal/bigdecimal.c#L2509开始 - 这是任何BigDecimal对象的初始化程序。如果您将该代码跟随下一个方法,即BigDecimal_new,您会注意到,在传递整数参数时,在分配和创建内部大小数对象之前还需要执行一些步骤,而不是在传递字符串参数时。

In any case, you shouldn't worry about loss of precision - the significant digits attributes are more like hints than absolute values. Even the documentation mentions it: The actual number of significant digits used in computation is usually larger than the specified number.

在任何情况下,您都不必担心精度损失 - 有效数字属性更像是提示而不是绝对值。甚至文档都提到它:计算中使用的实际有效位数通常大于指定的数字。

#1


3  

If you can read C code, you can start at https://github.com/ruby/ruby/blob/trunk/ext/bigdecimal/bigdecimal.c#L2509 - that's the initializer for any BigDecimal object. If you follow that code to the next method, which is BigDecimal_new you'll notice that when passed an integer argument there are a few more steps to go through before allocating and creating an internal big decimal object as opposed to when passing a string argument.

如果您可以阅读C代码,可以从https://github.com/ruby/ruby/blob/trunk/ext/bigdecimal/bigdecimal.c#L2509开始 - 这是任何BigDecimal对象的初始化程序。如果您将该代码跟随下一个方法,即BigDecimal_new,您会注意到,在传递整数参数时,在分配和创建内部大小数对象之前还需要执行一些步骤,而不是在传递字符串参数时。

In any case, you shouldn't worry about loss of precision - the significant digits attributes are more like hints than absolute values. Even the documentation mentions it: The actual number of significant digits used in computation is usually larger than the specified number.

在任何情况下,您都不必担心精度损失 - 有效数字属性更像是提示而不是绝对值。甚至文档都提到它:计算中使用的实际有效位数通常大于指定的数字。