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

标签 python numpy if-statement matplotlib

<分区>

这对我来说有点奇怪,我不确定如何正确地为问题命名。我有以下 MWE,它简单地生成一个坐标点列表 (x,t) 并执行一些检查以查看它们是否位于用户规定的边界上。特别是,如果 x[i] == 1.0t[i] != 0.0 那么程序应该打印一条声明。我似乎无法弄清楚为什么从未在此处输入 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")

最佳答案

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

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")

另外,我刚刚学习了 Python 3.5 添加的 isclose 函数,对这种情况很有用! 参见 this question/answer进行更多讨论。另请注意,如果您想对数组执行此操作,NumPy 提供了 allclose功能。

关于python - 如果 Python 中的条件未提供正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55012302/

相关文章:

python - 使用 matplotlib 的时间序列中的自定义日期范围(x 轴)

python - Numpy - 检查一个数组的元素是否属于另一个数组

java - 我该如何修复这段代码? (if 语句)

python - 在 Python.net 应用程序中安装自定义 IMessageFilter 时出现段错误

python - 对象文字是 Pythonic 的吗?

python - 如何根据最后一行/下一行过滤 Pandas 行?

python - opencv创建圈出界

r - 用户编写的函数将 NA 替换为 0,因为 for 循环在 r 中不起作用

javascript - 在 if 语句中循环变量条件

c# - C# 应用程序和 Python 应用程序之间通信的简单方法