Program not entering if statement

后端 未结 7 1831
走了就别回头了
走了就别回头了 2021-01-19 05:01

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):
        prin         


        
7条回答
  •  -上瘾入骨i
    2021-01-19 05:24

    Behold the power of the print statement...

    Let us insert a print statement...

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

    Running this program, and inspecting the output around 0 reveals the 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, it is never actually equal to zero!

    Solutions:

    1. Use integers. 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
      
    2. Never test equality with floating point arithmetic, but rather use a range:

      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
      

提交回复
热议问题