0

I am performing a simple sum operation on float numbers using math.fsum() function in Python but the result is not matching with what am expecting.

Please find the example below:

math.fsum([-5.2,-20.8,5,21])
#output : -8.881784197001252e-16

Ideally the output should be zero. What is the best way of calculating the sum of a list with both positive and negative float and int values? I have tried using sum and fsum. But in both the cases the outputs are not correct

math.fsum([-5.2,-20.8,5,21])
#output : -8.881784197001252e-16
Georgy
  • 12,464
  • 7
  • 65
  • 73
mal
  • 1
  • 2
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – dedObed Apr 05 '19 at 11:44
  • And [How to avoid floating point errors?](https://stackoverflow.com/questions/19473770/how-to-avoid-floating-point-errors) – Georgy Apr 05 '19 at 12:17
  • 1
    There's nothing wrong with `fsum` here: it's actually giving you _exactly_ the right answer in this case (with no rounding). The problem is with your input values: with decimal representations of binary floating-point (which is what Python is using under the hood), What You See Is Not What You Get. Thus the actual value stored for the numeric literal `-5.2` is, on a typical machine, `-5.20000000000000017763568394002504646778106689453125`, and similarly for `-20.8`. – Mark Dickinson Apr 05 '19 at 16:06
  • Look up "catastrophic cancellation". That is what happens there. – Rudy Velthuis Apr 05 '19 at 18:15

0 Answers0