将变量从数组传递给python中的scipy.integrate.quad() [英] Passing variable from an array to scipy.integrate.quad() in python

查看:503
本文介绍了将变量从数组传递给python中的scipy.integrate.quad()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python使函数适合我的数据集.在将积分scipy.integrate.quad()添加到函数的定义之前,我的代码使用curve_fit使函数起作用并使其拟合.我检查了为什么它会给我一个错误"提供的函数未返回有效的浮点数.",结果表明,如果我不从我所传递的数据集中传递变量,则代码可以正常工作我拟合我的曲线.如果我将任意值设置为5,如下所示:scipy.integrate.quad(args(5.))而不是Xi,它将再次正常运行.这是我的代码,请帮助我!

I'm using python to fit function to my dataset. My code worked and fitted function with curve_fit before I added integral scipy.integrate.quad() to the definition of function. I checked why does it give me an error "Supplied function does not return a valid float." and it turns out that the code works fine if I don't pass a variable from dataset over which I'm fitting my curve. If I set arbitrary value like 5. here: scipy.integrate.quad(args(5.)) instead of Xi it works perfectly again. Here is my code, help me please!:

from scipy import integrate
calka = lambda z, vz, t: np.exp(-1.*0.001-(z*0.001+vz*t*2.48138957816e-05))**2*1./((20.)**2)*np.exp(-(1.*1.42060911e-05-z*1.42060911e-05)**2*1./((20.)**2))

z_lin = linspace(0,zmax,npoints/2)

def func(Xi, vx, vz):
    z=0.0
    f=0.
    t=Xi
    f=integrate.quad(calka, z_lin[0], z_lin[3998], args=(vz,Xi))[0] #it works fine with arbitrarily set value
    q=(1.7*np.pi*4./1.569)**2*0.000024813
    v=(0.000024813)**2/((13.)**2)
    p=2.*2.*np.pi/1.569*0.000024813
    return np.exp(-vx*v*Xi)*np.exp(-(Xi*q*1.3))*np.cos(p*Xi*vz)*f

xdata = np.linspace(0, 1000, 1000)
print len(xdata)
ydata= autokowariancja[0,:]
popt, pcov = curve_fit(func, xdata, ydata)
print popt, pcov
plt.figure(figsize=(8,5))
pylab.plot(func(xdata, popt[0],  popt[1]), 'b')
pylab.plot(autokowariancja[0,:], 'r')
legend("NoWin","Win")
pylab.show()

推荐答案

我解决了这个问题. Xi是一个数组,而integrate.quad()仅采用浮点数,因此我通过枚举拆分了Xi数组,并创建了一个大小为Xi的数组,并分别为Xi的每个元素计算积分并将其传递到数组中:

I solved the problem. Xi is an array and integrate.quad() takes float only, so I splitted Xi array by enumerating it and I created an array the size of Xi and calculated integral for every element of Xi separately and passed it into an array:

def func(Xi, vx, vz):
    z=0.0
    f=0.
    t=Xi
    for i, item in enumerate(Xi):
        integral[i]=integrate.quad(calka, z_lin[0], z_lin[3998], args=(vz, Xi[i]))[0]
    q=(1.7*np.pi*4./1.569)**2*0.000024813
    v=(0.000024813)**2/((13.)**2)
    p=2.*2.*np.pi/1.569*0.000024813
    return np.exp(-vx*v*Xi)*np.exp(-(Xi*q*1.3))*np.cos(p*Xi*vz)*integral

这篇关于将变量从数组传递给python中的scipy.integrate.quad()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆