ruby 中的浮点精度 [英] Float precision in ruby
问题描述
我正在编写一个使用浮点数的 ruby 程序.我的精度有问题.例如
I'm writing a ruby program that uses floats. I'm having trouble with the precision. For example
1.9.3p194 :013 > 113.0 * 0.01
# => 1.1300000000000001
因此
1.9.3p194 :018 > 113 * 0.01 == 1.13
# => false
这正是我的应用需要正确计算的类型.
This is exactly the sort of calculation my app needs to get right.
这是预期的吗?我应该如何处理这个问题?
Is this expected? How should I go about handling this?
推荐答案
这是浮点数的固有限制(即使 0.01 也没有精确的二进制浮点表示).您可以使用 Aleksey 提供的技术,或者,如果您想要完美的精度,请使用 ruby 中捆绑的 BigDecimal 类.它更冗长,更慢,但它会给出正确的结果:
This is an inherent limitation in floating point numbers (even 0.01 doesn't have an exact binary floating point representation). You can use the technique provided by Aleksey or, if you want perfect precision, use the BigDecimal class bundled in ruby. It's more verbose, and slower, but it will give the right results:
require 'bigdecimal'
=> true
1.9.3p194 :003 > BigDecimal.new("113") * BigDecimal("0.01")
=> #<BigDecimal:26cefd8,'0.113E1',18(36)>
1.9.3p194 :004 > BigDecimal.new("113") * BigDecimal("0.01") == BigDecimal("1.13")
=> true
这篇关于ruby 中的浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!