使用 if 语句的 meshgrid 和用户定义函数的真值不明确

Ambiguous truth value for meshgrid and user-defined functions using if-statement

让我们假设我有一个函数 f(x,y) 足够平滑。然而,有些价值只存在于一种限制的意义上。举个例子sin(x)/ x x=0 的值仅存在于极限 x -> 0 中。 在一般情况下,我使用 if 语句处理此问题。

如果我在 meshgrid 的情节中使用它,我会收到一条错误消息:

ValueError: 具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

我真的需要 运行 两个 for 循环来填充 z 数组,还是有办法使用 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 数组的某些元素,您可以简单地使用索引,

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