程序不输入if语句

gsi*_*011 4 python floating-point

在我的python程序中,没有输入if语句.我已将代码简化为以下内容:

x = -5
while x < 5:
    if (x == 0):
        print 0
    x += .01
Run Code Online (Sandbox Code Playgroud)

该程序不输出任何内容.

但是,将最后一行更改为x + = .5会使程序输出0.问题是什么?

How*_*ard 9

浮点数表示可能不够准确.你永远不应该测试零平等,而是使用一些东西

if (abs(x) < 1E-10) ...
Run Code Online (Sandbox Code Playgroud)


And*_*yuk 7

看看印刷声明的力量......

让我们插入一份印刷声明......

x = -5
while x < 5:
    if (x == 0):
        print 0
    x += .01
    print x
Run Code Online (Sandbox Code Playgroud)

运行此程序,并检查0左右的输出显示问题:

...
-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
...
Run Code Online (Sandbox Code Playgroud)

哦,男孩,它实际上永远不会等于零!

解决方案:

  1. 使用整数.最可靠的.

    x = -500    # times this by a 100 to make it an integer-based program
    while x < 500:
      if (x == 0):
        print 0
      x += 1
    
    Run Code Online (Sandbox Code Playgroud)
  2. 永远不要使用浮点运算来测试相等性,而是使用范围:

    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
    
    Run Code Online (Sandbox Code Playgroud)