Ruby数学运算的精度问题 [英] Issue with precision of Ruby math operations
问题描述
您知道如何以数学精度解决以下问题吗?
Do you know how to fix the following issue with math precision?
p RUBY_VERSION # => "1.9.1"
p 0.1%1 # => 0.1
p 1.1%1 # => 0.1
p 90.0%1 # => 0.0
p 90.1%1 # => 0.0999999999999943
p 900.1%1 # => 0.100000000000023
p RUBY_VERSION # => "1.9.2"
p 0.1%1 # => 0.1
p 1.1%1 # => 0.10000000000000009
p 90.0%1 # => 0.0
p 90.1%1 # => 0.09999999999999432
p 900.1%1 # => 0.10000000000002274
推荐答案
大十进制
正如 man 所说;
Big Decimal
As the man said;
将无限多个实数压缩为有限数量的位需要近似表示.
Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation.
I have however had great success using the BigDecimal class. To quote its intro
Ruby为任意精度的整数算术提供了内置支持.例如:
Ruby provides built-in support for arbitrary precision integer arithmetic. For example:
42 ** 13-> 1265437718438866624512
42**13 -> 1265437718438866624512
BigDecimal为非常大或非常准确的浮点数提供了类似的支持.
BigDecimal provides similar support for very large or very accurate floating point numbers.
以您的示例之一;
>> x = BigDecimal.new('900.1')
=> #<BigDecimal:101113be8,'0.9001E3',8(8)>
>> x % 1
=> #<BigDecimal:10110b498,'0.1E0',4(16)>
>> y = x % 1
=> #<BigDecimal:101104760,'0.1E0',4(16)>
>> y.to_s
=> "0.1E0"
>> y.to_f
=> 0.1
如您所见,确保适当的精度是可能的,但这需要一点努力.
As you can see, ensuring decent precision is possible but it requires a little bit of effort.
这篇关于Ruby数学运算的精度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!