我对以下问题有疑问:
我想绘制以下简单函数:
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值为true。这似乎有效。
有人知道这个警告来自哪里吗?
答案 0 :(得分:0)
正如已经指出的那样,您将使用np.where()
评估每个案例。为了避免错误,只需将其编码为较低级别,例如
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def f(x1, x2):
shape = np.shape(x1)
y = np.zeros(shape)
for i in range(0,shape[0]):
for j in range(0,shape[1]):
if x1[i,j]!=0 and x2[i,j]!=0:
y[i,j] = x1[i,j]*x2[i,j]/(x1[i,j]*x1[i,j]+x2[i,j]*x2[i,j])
return y
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()