如果 Python 中的条件未提供正确的结果

use*_*323 4 python if-statement numpy matplotlib

这对我来说是一个有点奇怪的问题,我不确定如何正确地命名这个问题。我有以下 MWE,它只是生成坐标点列表(x,t)并执行一些检查以查看它们是否位于用户指定的边界上。特别是, ifx[i] == 1.0t[i] != 0.0then 程序应该打印一条声明来说明这一点。我似乎无法弄清楚为什么if这里从未输入条件。我已经打印出值对x[i]t[i]验证是否确实存在满足条件的值对......

#Load Modules
import numpy as np
import math, random
from pylab import meshgrid

# Create the arrays x and t on an evenly spaced cartesian grid
N = 10
xa = -1.0;
xb = 1.0;

ta = 0.0;
tb = 0.4;

xin = np.arange(xa, xb+0.00001, (xb-xa)/N).reshape((N+1,1))
tin = np.arange(ta, tb+0.00001, (tb-ta)/N).reshape((N+1,1))

X_tmp,T_tmp = meshgrid(xin,tin)
x = np.reshape(X_tmp,((N+1)**2,1))
t = np.reshape(T_tmp,((N+1)**2,1))

# create boundary flags
for i in range(0,(N+1)**2):
    if (x[i] == xb and t[i] != ta):
        print("We are on the right-side boundary")
Run Code Online (Sandbox Code Playgroud)

aga*_*rs3 5

我认为您遇到了浮点精度问题。因此,虽然x[i]非常接近,但并不完全等于xb。完美的相等测试会导致浮点数出现这样的问题。您想要的是测试这些值之间的差异是否很小。尝试这个:

ep = 1e-5 # choose this value based on how close you decide is reasonable
for i in range(0,(N+1)**2):
    if (abs(x[i] - xb) < ep and abs(t[i] - ta) > ep):
       print("We are on the right-side boundary")
Run Code Online (Sandbox Code Playgroud)

另外,我刚刚学习了 Python 3.5 添加了isclose对这种情况有用的函数!请参阅此问题/答案以获取更多讨论。另请注意,如果您想对数组执行此操作,NumPy 提供了该allclose函数。