用整数拟合方程,其中上限为变量

时间:2018-11-25 20:51:54

标签: python curve-fitting integral

我正在尝试拟合具有积分的方程。积分的上限是一个变量,因此我在使用Quad时遇到了麻烦,因为它只接受浮点数作为限制。我曾尝试使用for循环解决此问题,但仍然会遇到相同的错误'ValueError:具有多个元素的数组的真值不明确。使用a.any()或a.all()'。

我要拟合的方程是:

Fit Equation

我知道常数M和c,并且有m(z)和z的数据。我正在尝试拟合ΩM和ΩΛ。 这是我的代码:

import numpy as np
import scipy.integrate as integrate
from scipy.optimize import curve_fit

z=[0.03, 0.05, 0.026, 0.075, 0.026, 0.014, 0.101, 0.02, 0.036, 0.045, 0.043, 0.018, 0.079, 
0.088, 0.063, 0.071, 0.052, 0.05]
m=[16.26, 17.63, 16.08, 18.43, 16.28, 14.47, 19.16, 15.18, 16.66, 17.61, 17.19, 15.61, 
18.27, 19.28, 18.24, 18.33, 17.54, 17.69]
c=299792.458 #speed of light
M=-18.316469239 

def integrand(Z,OM,OV):
    return np.power((((1+Z)**2)*(1+OM*Z)-Z*(2+Z)*OV),-0.5)

def curve(z,OM,OV):
    for i in z:
        I=integrate.quad(integrand,0,i,args=(OM,OV))[0]
    return M+5*np.log10(c*(1+z))*I)                       

popts, pcov=curve_fit(curve,z,m)

预先感谢,希望其中包括一切!

1 个答案:

答案 0 :(得分:0)

除了评论外,您仅考虑积分循环的最后结果。更正后的代码应如下所示:

from matplotlib import pylab as plt

import numpy as np
import scipy.integrate as integrate
from scipy.optimize import curve_fit

z=np.asarray([0.03, 0.05, 0.026, 0.075, 0.026, 0.014, 0.101, 0.02, 0.036, 0.045, 0.043, 0.018, 0.079, 
0.088, 0.063, 0.071, 0.052, 0.05])
m=np.asarray([16.26, 17.63, 16.08, 18.43, 16.28, 14.47, 19.16, 15.18, 16.66, 17.61, 17.19, 15.61, 
18.27, 19.28, 18.24, 18.33, 17.54, 17.69])

# sorting of the data is not necessary but nicer when plotting
idx = np.argsort(z)
z = np.take(z, idx)
m = np.take(m, idx)

c=299792458 #speed of light
M=-18.316469239 

def integrand(Z,OM,OV):
    return np.power((((1+Z)**2)*(1+OM*Z)-Z*(2+Z)*OV),-0.5)

def curve(z,OM,OV):
    I = [integrate.quad(integrand,0,i,args=(OM,OV))[0] for i in z]
    return M+5*np.log10(c*(1+z)*I)

popts, pcov=curve_fit(curve,z,m, p0=(1,1))

plt.plot(z,m,'o')
plt.plot(z,curve(z,*popts))
plt.show()

实际上,它提供了很好的匹配:

data with fit