2014-10-20 51 views
1

我使用numpy的電源功能,並且我正在獲取警告消息。這是代碼:運行時警告使用Numpy電源

import numpy as np 


def f(x, n): 
    factor = n/(1. + n) 
    exponent = 1. + (1./n) 
    f1_x = factor * np.power(0.5, exponent) - np.power(0.5 - x, exponent) 
    f2_x = factor * np.power(0.5, exponent) - np.power(x - 0.5, exponent) 
    return np.where((0 <= x) & (x <= 0.5), f1_x, f2_x) 

fv = np.vectorize(f, otypes='f') 
x = np.linspace(0., 1., 20) 
print(fv(x, 0.23)) 

這是警告消息:

E:\ ProgramasPython3 \ LibroCientifico \ partesvectorizada.py:8: RuntimeWarning:在功率f2_x =因數遇到無效值* np.power(0.5,exponent) - np.power(x - 0.5,指數) E:\ ProgramasPython3 \ LibroCientifico \ partesvectorizada.py:7: RuntimeWarning:電源遇到的無效值f1_x =因子* np.power (0.5,指數) - np.power(0.5 - x,指數)[-0.0199636 -0.00895462 -0.0023446 0.00136486 0.003271 0.00414007 0.00447386 0.00457215 0.00459036 0.00459162 0.00459162 0.00459036 0.00457215 0.00447386 0.00414007 0.003271 0.00136486 -0.0023446 -0.00895462 -0.0199636]

我不知道什麼是無效值。我不知道如何指定numpy函數f2_x僅適用於> 0.5和< = 1.0之間的值。 謝謝

+0

它對我來說運行良好 - Python 3.4.1,numpy 1.9.0,Win8 – MattDMo 2014-10-20 21:08:31

回答

2

發生這種情況的原因是因爲您試圖採取負數的非整數次冪。顯然這在Python/Numpy的早期版本中不起作用,如果您沒有明確地將該值設置爲複雜的話。所以,你將不得不做一些像

np.power(complex(0.5 - x), exponent) .real

編輯:因爲你的價值觀將是真正複雜的(不是有些實數+一些微小的IMAG部分),我想你會想要麼稍後使用複合體(但後來的<=)會遇到困難,或者您想要以某種其他方式捕捉基底爲負的情況。

+1

+1或者你可以簡單地執行'x = x.astype(np.complex128)' – 2014-10-21 06:07:14

+0

我已經安裝了numpy,但是我獲得相同的錯誤添加實際。奇怪的是,我使用Windows 8.1 64位和Pycharm檢測到我numpy 0.8,但我已經安裝了Python 3.4.2 64位的最新版本。謝謝 – Tobal 2014-10-21 20:19:37

+0

@Tobal你還把'complex()'cast嗎?這實際上是重要的一部分。如果這不起作用,請嘗試@Saullo Castro的版本。我很確定負面的觀點是這個問題(我在嘗試時遇到同樣的錯誤)。 – greschd 2014-10-21 22:11:04

0

好,非常感謝大家很多,這裏是使用針對從numpy的其中一個分段函數,並使用np.complex128解決方案提到@Saullo

import numpy as np 


    def f(x, n): 
     factor = n/(1. + n) 
     exponent = (n + 1.)/n 
     f1_x = lambda x: factor * \ 
      np.power(2., -exponent) - np.power((1. - 2. * x)/2., exponent) 
     f2_x = lambda x: factor * \ 
      np.power(2., -exponent) - np.power(-(1. - 2. * x)/2., exponent) 
     conditions = [(0. <= x) & (x <= 0.5), (0.5 < x) & (x <= 1.)] 
     functions = [f1_x, f2_x] 
     result = np.piecewise(x, conditions, functions) 
     return np.real(result) 

    x = np.linspace(0., 1., 20) 
    x = x.astype(np.complex128) 
    print(f(x, 0.23)) 

問題是,當從電源底座是負數,那麼np.power無法正常工作,並且您會收到警告消息。我期望這對每個人都有用。