2

I have a Python script which saves measurement values in a csv file. I then read the csv into another python script which checks whether the results sum up to 1.0. I noticed that my comparison script often returns false, even though if I do print(my_sum), the printed result is 1.0. Similarly, summing up the values using excel gives exactly 1.0.

Here are my example values:

x = 0.926119895097366
y = 0.0248330035844995
z = 0.0490471013181347

The check if (x+y+z) == 1.0 failed. However, when I do print(x+y+z), the value printed is 1.0. Similarly, using excel to sum those values gives 1.0. However, when I run the summation in Ipython, the result is 1.0000000000000002. What is causing it?

Ziva
  • 3,181
  • 15
  • 48
  • 80
  • 2
    https://stackoverflow.com/questions/588004/is-floating-point-math-broken might be helpful – jkr Apr 24 '21 at 17:42
  • 1
    floating point arithmetic is fun like that, never compare with a specific value, use for example [math.isclose](https://docs.python.org/3/library/math.html#math.isclose) – Copperfield Apr 24 '21 at 17:45

1 Answers1

2

You cannot, for typical use cases such as the results of arithmetic operations, compare floats for equality due to rounding errors.

Instead check that the two numbers are very close. See this for alternatives.

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147