我有这个代码来定义一个函数
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
但我在xdata = [1,2,3,4,5]行得到语法错误我在做错什么
答案 0 :(得分: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
,只需将其分解为较小的块。
答案 1 :(得分: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))))