#### Curve-Fitting over an integral containing both a data array and function in python

``````def integrand(tm, Pm, args):
dt, alpha1, alpha2 = args
return Pm*(1-np.e**( -(alpha1 * (tm+dt))) )*np.e**(-(alpha2 * (tm+dt)))
``````

tm是积分变量，而dt，alpha1，alpha2是未知常数，积分范围为0到tm。

1 个回复

``````from scipy.optimize import leastsq
import numpy as np

Pm = np.array( [ float(v) for v in open( "impulse_data.txt", "r" ).readlines() ] )
print type(Pm), Pm.shape

tm = np.array( [ float(v) for v in open( "Impulse_time_axis.txt", "r" ).readlines() ] )
print type(tm), tm.shape

output = np.array( [ float(v) for v in open( "Output_data.txt", "r" ).readlines() ] )
print type(output), output.shape

tout = np.array( [ float(v) for v in open( "Output_time_axis.txt", "r" ).readlines() ] )
print type(tout), tout.shape

# Define the function that calculates the residuals
def residuals(  coeffs, output, tm ):
dt, alpha1, alpha2 = coeffs
res = np.zeros( tm.shape )
for n,t in enumerate(tm):
# integrate to "t"
value = sum( Pm[:n]*(1-np.e**( -(alpha1 * (tm[:n]+dt))) )*np.e**(-(alpha2 * (tm[:n]+dt))) )
# retrieve output at t+dt
n1 = (np.abs(tout - (t+dt) )).argmin()
# construct the residual
res[n] =  output[n1] - value
return res

# Initial guess for the parameters
x0 = (10.,1.,1.)

# Run the least squares routine
coeffs, flag = leastsq( residuals, x0, args=(output,tm) )

# Report the results
print( coeffs )
print( flag )
``````
1 Python：根据数据进行曲线拟合

2 使用已知积分Python进行曲线拟合

3 如何使用Python进行曲线拟合？

5 如何使用python/scipy对曲线族进行曲线拟合

7 使用 Scipy 在 Python 中拟合曲线

9 如何自动选择数据进行曲线拟合