首页 文章

用python中的积分方程拟合数据

提问于
浏览
0

我有一些数据,我试图适应包含和定积分方程的模型 . 我的策略是使用optimize.leastsq和integrate.quad,我不断收到类型错误:“只有length-1数组可以转换为Python标量”

任何帮助将不胜感激 .

这是我的代码的相关部分(请记住self.vvals和self.bvals是一维数组,self.L是一个浮点数):

def NLFit(self):
    '''fits data to the NL formula'''
    L=self.L

    def model(m0,m1,m2,B): #m0=So, m1=D, m2=NLtau
        return scipy.integrate.quad(lambda t: -m0/(math.sqrt(4*math.pi*m1*t))*math.exp(-   L**2/(4*m1*t))*math.exp(-t/m2)*math.cos(g*muB*B*t/h) , 0, 1e-9)

    def residuals(p,y,x): 
        m0,m1,m2=p
        err=y-model(m0,m1,m2,x)
        return err

    def peval(x,p):
        return model(p[0],p[1],p[2],x)

    #initial conditions
    p0=[1,1,1]

    #find fit
    B=self.bvals
    V=self.vvals
    plsq=scipy.optimize.leastsq(residuals,p0,args=(V,B))

    print plsq[0]

1 回答

  • 0

    使用 numpy 可能有所帮助 .

    Numpy permet de“vectoriser”,即appliquer unefonctionàunvecteur / matriceetéviterlesboucles . Comme nous avons choisi d'utiliserNumpyàtraversimport numpy as np,il faut choisir les fonctionsusuellesdéfiniesdansNumpy

    >>> from math import cos
    >>> a=np.arange(4, dtype=float)
    >>> a array([ 0.,  1.,  2.,  3.])
    >>> cos(a) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: only length-1 arrays can be converted to Python scalars
    >>> np.cos(a) array([ 1.        ,  0.54030231, -0.41614684, -0.9899925 ])
    

    This is fom help files.

相关问题