浮点除法的不同结果

Different results in floating point division

为什么下面每次计算的最后一位都不同?他们不应该是一样的吗?

1.0 / 3   # => 0.3333333333333333
10.0 / 3  # => 3.3333333333333335
100.0 / 3 # => 33.333333333333336

浮点数不能精确表示所有的实数,浮点运算也不能精确表示真正的算术运算,这就导致了很多令人吃惊的情况。

我建议阅读:https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

您可以使用 BigDecimal 代替浮点数来解决大部分问题

require 'bigdecimal'
BigDecimal.new(  '1.0') / 3    #=>  0.333333333333333333
BigDecimal.new( '10.0') / 3    #=>  3.333333333333333333
BigDecimal.new('100.0') / 3    #=> 33.333333333333333333
1.0/3 * 10 == 10.0/3 # => false

浮点数不准确,因此,在当前版本的 Ruby 中简化了 Rationals 的使用:

1/3r * 10 == 10/3r # => true