0

I would like to test a set of 3 variables w1,w2,w3. When the sum of these is equal to 1, I want to print "YATTA".

import numpy as np

for w1 in np.arange(0.10,0.45,0.05):
       for w2 in np.arange(0.10,0.45,0.05):
           for w3 in np.arange(0.10,0.45,0.05):
               sumw=w1+w2+w3
               if(sumw==1.0):
                   print "YATTA"
               else:
                   print w1,w2,w3,sumw

When I run this I observe something very weird! For example when my variables are :

w1 = 0.2
w2 = 0.4
w3 = 0.4

sumw is 1.0 BUT it's not printing "YATTA" and instead the else statement is executed.

Why does my code behave like this, and how would I solve this issue?

Simon Gibbons
  • 6,969
  • 1
  • 21
  • 34

1 Answers1

3

Looks like you have fallen foul of the fact that floating point arithmetic isn't exact.

See this question for a good explanation why you are getting the results you are.

The quick explanation of your particular case is that, and your decimals cannot be converted exactly into binary so w1, w2 and w3 are not exactly what you think they are. More generally: most real numbers cannot be represented in a finite number of digits, and most floating point operations must have rounding.

As a fix, instead of comparing floats for equality as you are doing now instead use the np.isclose function instead

np.isclose(sumw, 1.0)
Community
  • 1
  • 1
Simon Gibbons
  • 6,969
  • 1
  • 21
  • 34