使用if语句的网格和用户定义函数的含糊真值 [英] Ambiguous truth value for meshgrid and user-defined functions using if-statement
问题描述
让我们假设我的函数 f(x,y)
足够平滑.但是,某些值仅在极限的意义上存在.以例如sin(x)/x
x=0
的值只存在于极限 x -> 0 内.在一般情况下,我用 if
语句处理此问题.
Let's assume that I have a function f(x,y)
being sufficiently smooth. Yet some values only exist in the sense of a limit. Take e.g. sin(x)/ x
the value for x=0
only exists in the limit x -> 0.
In the general case I handle this with an if
statement.
如果我在带有 meshgrid
的情节中使用它,则会收到错误消息:
If I use this in a plot with meshgrid
I get an error message:
ValueError:包含多个元素的数组的真值不明确.使用 a.any() 或 a.all()
我真的必须运行两个 for
循环来填充 z-array 还是有办法使用 meshgrid
?
Do I really have to run two for
loops to fill an z-array or is there a way to use meshgrid
?
最小工作示例:
import matplotlib.pyplot as plt
import numpy as np
def test(x,y):
a=1.0/(1+x*x)
if y==0:
b=1
else:
b=np.sin(y)/y
return(a * b)
if __name__=='__main__':
X = linspace(-5, 5, 100)
Y = linspace(-5, 5, 100)
X,Y = meshgrid(X, Y)
Z =test(X,Y)
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1,1,1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.25)
plt.show()
推荐答案
要仅将值分配给 Numpy 数组的某些元素,您可以简单地使用索引,
To assign values only to some elements of a Numpy array you can simply use indexing,
import numpy as np
def test(x, y):
a = 1.0/(1+x*x)
b = np.ones(y.shape)
mask = (y!=0)
b[mask] = np.sin(y[mask])/y[mask]
return a*b
这篇关于使用if语句的网格和用户定义函数的含糊真值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!