Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 523
Ilya Cherevkov Avatar asked May 14 '18 21:05

Ilya Cherevkov


People also ask

How do you sum all the numbers in an array in Ruby?

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.

What does .inject do in Ruby?

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.

Which of the following can be used in Ruby to find the sum of all elements in the integer array?

You can use the aptly named method Enumerable#sum .

How do you find the sum in Ruby?

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.


1 Answers

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.

like image 135
meagar Avatar answered Oct 05 '22 18:10

meagar