Ruby:sum 与 inject(:+) 产生不同的结果

Ruby: sum vs. inject(:+) produces different results

我注意到 array.sumarray.inject(:+) 产生了不同的结果。这是什么原因?

a = [10, 1.1, 6.16]

a.inject(:+)
# => 17.259999999999998

a.sum
# => 17.26

当某些输入是浮点数时,Array#sum 的 C 实现委托给 Kahan summation algorithm

这个算法...

...significantly reduces the numerical error in the total obtained by adding a sequence of finite precision floating point numbers, compared to the obvious approach. This is done by keeping a separate running compensation (a variable to accumulate small errors).

-- Wikipedia

Array#sum and the implementation on Github