用积分拟合方程,其中上限是一个变量

Fitting an equation with an integral, where upper limit is a variable

我正在尝试拟合具有积分的方程。积分的上限是一个变量,因此我在使用 quad 时遇到了麻烦,因为它只接受浮点数作为限制。我试图使用 for 循环来解决这个问题,但我仍然不断收到 'ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()'.

的相同错误

我要拟合的方程是:

我知道常数 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)

在此先感谢并希望包括所有内容!

除了注释之外,您只考虑了积分循环的最后结果。更正后的代码应该是这样的:

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()

确实匹配得很好: