2017-06-01 49 views
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值作爲真。這似乎工作。

有沒有人知道這個警告來自哪裏?

+0

我無法重現它。你的代碼適合我,並繪製一張圖 – MaxU

+0

'np.where()'的參數都是*評估*,所以像這樣使用它不會消除錯誤。 –

+0

@WarrenWeckesser如果我正確地理解了你'x1 * x2 /(x1 * x1 + x2 * x2)'也會評估x1 = x2 = 0。你知道比np.where()更好的解決方法嗎? –

回答

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()