I've noticed array.sum
and array.inject(:+)
produce different results. What's the reason for this?
a = [10, 1.1, 6.16]
a.inject(:+)
# => 17.259999999999998
a.sum
# => 17.26
Use Array#inject to Sum an Array of Numbers in Ruby To calculate the sum of an array in Ruby versions before 2.4. 0, we must use inject or its alias reduce . inject is a function that takes an initial value and a block. The accumulation is the first block argument, and the current number is the second.
When called, the inject method will pass each element and accumulate each sequentially. To break this down even further, inject takes the first element in your collection and uses that as the base 'sum'. It then takes the next element (or the second element in the array) and then adds them together.
You can use the aptly named method Enumerable#sum .
Ruby | Enumerable sum() function The sum() of enumerable is an inbuilt method in Ruby returns the sum of all the elements in the enumerable. If a block is given, the block is applied to the enumerable, then the sum is computed. If the enumerable is empty, it returns init. Parameters: The function accepts a block.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With