Skip to main content
 首页 » 编程设计

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

2025年05月04日10java哥

假设我有一个足够平滑的函数 f(x,y)。然而,有些值(value)只存在于一种限制的意义上。举个例子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