为什么以下内容适用于 ruby?

Why the following works in ruby?

to_a 在整数范围内的行为在这种情况下有所不同。 最多 15 位小数,include? returns false 但一旦达到 16 位小数,数组就会将小数位视为数组的一部分。

Why?

2.2.1 :020 > (1..9).to_a.include?(8.999999999999999)
 => false 
2.2.1 :021 > (1..9).to_a.include?(8.9999999999999999)
 => true 
2.2.1 :022 >

And why range only says this is true

2.2.1 :001 > (1..9).include?(8.9)
 => true 

(1..9).include?(8.9)1 <= 8.9 && 8.9 <= 9 相同。我认为这个 returns true 的原因很明显。

但是(1..9).to_areturns数组[1,2,3,4,5,6,7,8,9]。这导致了另一个观察结果:

8.999999999999999 == 9   #=> false
8.9999999999999999 == 9  #=> true

Floating point shenanigans.

您可能想使用 next_float 来调查下一个可表示的浮点数(正如 Tom Lord 在评论中指出的那样):

8.999999999999999.next_float   #=> 9.0
8.9999999999999999.next_float  #=> 9.000000000000002

Et voilà.