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

但是我在 xdata=[1,2,3,4,5] 行遇到语法错误我在做什么错

4

2 回答 2

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分解为更小的块来从公式中删除重复项。

于 2013-03-19T17:44:54.370 回答
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))))
于 2013-03-19T17:59:50.863 回答