Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program not entering if statement

In my python program, an if statement is not being entered. I have simplified the code to the following:

x = -5
while x < 5:
    if (x == 0):
        print 0
    x += .01

This program does not output anything.

However, changing the last line to x += .5 makes the program output 0. What's the problem?

like image 511
gsingh2011 Avatar asked Nov 29 '22 03:11

gsingh2011


1 Answers

Floating point number representation might not be accurate enough. You should never test for zero equality but instead use something along

if (abs(x) < 1E-10) ...
like image 199
Howard Avatar answered Dec 05 '22 02:12

Howard