The program is not included in the if statement

In my python program, the if statement is not entered. I simplified the code as follows:

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

This program does not display anything.

However, changing the last line to x + = .5 makes the program exit 0. What is the problem?

+4
source share
7 answers

The number of floating point numbers may not be accurate enough. You should never check for null equality, but instead use something along

if (abs(x) < 1E-10) ...
+9
source

Here is the power of print approval ...

Insert print instruction ...

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

Running this program and checking the output around 0 detects a problem:

...
-0.13
-0.12
-0.11
-0.1
-0.0900000000001
-0.0800000000001
-0.0700000000001
-0.0600000000001
-0.0500000000001
-0.0400000000001
-0.0300000000001
-0.0200000000001
-0.0100000000001
-6.23077978101e-14
0.00999999999994
0.0199999999999
0.0299999999999
0.0399999999999
0.0499999999999
0.0599999999999
0.0699999999999
0.0799999999999
0.0899999999999
0.0999999999999
0.11
0.12
0.13
...

Oh boy, he is never equal to zero!

Solutions:

  • Use integers. The most reliable.

    x = -500    # times this by a 100 to make it an integer-based program
    while x < 500:
      if (x == 0):
        print 0
      x += 1
    
  • , :

    delta = 0.00001 #how close do you need to get
    point = 0 #point we are interested in
    if  (point-delta) <= x <= (point+delta):
        # do stuff
    
+7

- , x 0,0000000000....

if (x == 0): if -0.001 < x < 0.001:

BTW, python if.

: -1 1 0,01 , : 7.52869988574e-16.

+3

, . , Decimal:

from decimal import Decimal

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

0, .

. Decimal(.01), 0.01, , .

+3

.01 , .5 .

, , 1/3 .333333 1/3 , 1. 0,999999, 1.

, 100% , , .

0
-0.01
7.52869988574e-16
0.01

x > -.001 x <.001 -

0

, ( 2) . , , 0.01 , . 0.01 float :

0.01 * 2 = 0.02 [0]
0.02 * 2 = 0.04 [0] 
0.04 * 2 = 0.08 [0]
0.08 * 2 = 0.16 [0]
0.16 * 2 = 0.32 [0]
0.32 * 2 = 0.64 [0]
0.64 * 2 = 1.28 [0]
0.28 * 2 = 0.56 [0]
0.56 * 2 = 1.12 [1]
...

, , , . , , , . , , , (, , ). , , , , . x + = 0.01 . 0,5 :

0.5 * 2 = 1.0 [1]

So, the binary equivalent of 0.5 float is 0.1 . Since it is perfectly represented in binary format on your computer. You will get the exact result.

This has nothing to do with your code or python. This is just the way computer hardware works :)

0
source

All Articles