2013-03-19 59 views
0

我有這樣的代碼來定義一個函數爲什麼在定義函數後出現語法錯誤?

def f(Frequency,Omegahot,Beta,Omegacold,Thot,Tcold): 
    C=300000000 
    k=1.38E-23 
    h=6.062E-34 
    return(Omegahot*numpy.power(Frequency,Beta))*((2*h*numpy.power(Frequency,3)/(C**2)))*(1/(numpy.exp(h*Frequency/(k*Thot))-1)) + (Omegacold*numpy.power(Frequency,Beta)*((2*h*numpy.power(Frequency,3)/(C**2)))*(1/(numpy.exp(h*Frequency/(k*Tcold))-1)) 

xdata=[1,2,3,4,5] 
popt, pcov = curve_fit(f,xdata,fluxs,p0=None,) 
print popt 

但我在該行擴展數據出現語法錯誤= [1,2,3,4,5]我在做什麼錯

+5

[PEP-8建議限制一行到長79個字符。](http://www.python.org/dev/peps/pep-0008/#maximum-line-length),應考慮用一些臨時變量將你的大量方程分解成多行,以使它更易讀,並使這樣的錯誤更容易調試。 – 2013-03-19 17:47:00

回答

5

括號上一行是不均衡的,在年底再增加一個修復

return (Omegahot*numpy.power(Frequency,Beta))*((2*h*numpy.power(Frequency,3)/(C**2)))*(1/(numpy.exp(h*Frequency/(k*Thot))-1)) + (Omegacold*numpy.power(Frequency,Beta)*((2*h*numpy.power(Frequency,3)/(C**2)))*(1/(numpy.exp(h*Frequency/(k*Tcold))-1))) 

但配方是亂七八糟的一點點找出其中他們真正的歸屬。

你真的想要這個公式分解成一個80字符的行內的一些配件,並使用臨時變量:

temp1 = Omegahot * numpy.power(Frequency, Beta) 
temp2 = 2 * h * numpy.power(Frequency, 3)/(C ** 2) 
temp3 = 1/(numpy.exp(h * Frequency/(k * Thot)) - 1) 
temp4 = Omegacold * numpy.power(Frequency, Beta) * 
temp5 = 1/(numpy.exp(h * Frequency/(k * Tcold)) - 1) 
return (temp1 * temp2 * temp3) + (temp4 * temp2 * temp6) 

但具有更好的變量名。我已經設法從公式中刪除重複的temp2,只是把它分解成更小的塊。

+0

你是否認爲它試圖做快捷方式並從其他地方複製它從來沒有真正的作品 – user2187702 2013-03-19 17:53:15

0

可讀性計數。這是重寫你的函數的一種方法,它更具可讀性。通過預先計算出現多次的表達式,您將需要更少的圓括號,並使計算速度更快。

import numpy as np 
def f(Frequency, Omegahot, Beta, Omegacold, Thot, Tcold, exp=np.exp, power=np.power): 
    C = 300000000 
    k = 1.38E-23 
    h = 6.062E-34 
    fb = power(Frequency, Beta) 
    f3 = power(Frequency, 3) 
    C2 = C ** 2 
    C3 = fb * 2 * h * f3/C2 
    hF = h * Frequency 
    return ((Omegahot * C3/(exp(hF/(k * Thot)) - 1)) 
      + (Omegacold * C3/(exp(hF/(k * Tcold)) - 1)))) 
相關問題