As a homework, I've implemented the following sum
function to return the sum of a list of numbers:
defmodule Homework do
@spec sum(list(number())) :: number()
def sum(l) do
case l do
[] -> 0
[a | as] -> a + sum(as)
end
end
end
And as a unit test I've used the following comparison:
[-2, -2.1524700989447303, 1] |> fn(l) -> Enum.sum(l) === Homework.sum(l) end.()
And this test fails, returning false
. When I ran the functions in iex
I got the following result, which is surprising for me:
iex(1)> [-2, -2.1524700989447303, 1] |> Enum.sum
-3.1524700989447307
iex(2)> [-2, -2.1524700989447303, 1] |> Homework.sum
-3.1524700989447303
What is more, both functions consistently generate -3.1524700989447307
and -3.1524700989447303
, respectively.
Why does this difference happens?
Edit
The question Why does changing the sum order returns a different result? pointed me in the right direction but I think that the actual answer to this question (an implementation detail in OTP) could be interesting to someone as well.