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

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


The C implementation of Array#sum delegates to the Kahan summation algorithm when some of its inputs are floating point numbers.

This 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

See Array#sum and the implementation on Github.