0
我有一個關於下列問題一個問題:python:在true_divide中遇到無效值 - 但在哪裏?
我想繪製以下簡單的函數:
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值作爲真。這似乎工作。
有沒有人知道這個警告來自哪裏?
我無法重現它。你的代碼適合我,並繪製一張圖 – MaxU
'np.where()'的參數都是*評估*,所以像這樣使用它不會消除錯誤。 –
@WarrenWeckesser如果我正確地理解了你'x1 * x2 /(x1 * x1 + x2 * x2)'也會評估x1 = x2 = 0。你知道比np.where()更好的解決方法嗎? –