【发布时间】:2017-06-01 19:13:08
【问题描述】:
我有一个关于以下问题的问题:
我想绘制以下简单函数:
f(x) = x_1*x_2/(x_1^2+x_2^2)
如果 x & y 为零,你会除以零,所以我添加了一个例外来防止这种情况:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def f(x1, x2):
return np.where(np.logical_and(x1==0,x2==0),
0,
x1*x2/(x1*x1+x2*x2))
n = 3
x = y = np.linspace(-5,5,n)
xv, yv = np.meshgrid(x, y)
z = f(xv,yv)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(xv,yv,z)
plt.show()
我的数字是情节,如果我检查我的解决方案,它似乎也是正确的。但是,如果我运行代码,则会出现除法错误:
RuntimeWarning: invalid value encountered in true_divide
我已经手动测试了 np.where 函数,它将 x_1=x_2=0 值返回为真。这似乎行得通。
有人知道这个警告来自哪里吗?
【问题讨论】:
-
我无法复制它。你的代码对我来说很好,并绘制了一个图表
-
np.where()的参数都是求值的,所以这样使用并不能消除错误。 -
@WarrenWeckesser 如果我理解正确,'x1*x2/(x1*x1+x2*x2)' 也被评估为 x1=x2=0。你知道比 np.where() 更好的方法来解决这个问题吗?
标签: python numpy scientific-computing