Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To perform curve fitting for an integral function that has varying integration limits using Python, one can follow these steps:

  1. Define the integral function that needs to be fit. Let's say the integral function is:

    f(x) = int(sin(x*t)/t, t=a(x)..b(x))

    Here a(x) and b(x) are the lower and upper limits of integration, respectively, which vary with x.

  2. Generate some test data for x, a(x) and b(x). For example,

    import numpy as np
    
    x = np.linspace(0, 10, 100)
    a = 0.5*x
    b = np.sin(x)
    
  3. Define a function that returns the integral function using sympy.integrate.

    from sympy import symbols, integrate
    
    def F(t, a, b):
       return integrate(np.sin(t*x)/t, (t, a, b))
    

    Here t is the integration variable that needs to be defined as a sympy symbol.

  4. Use scipy.optimize.curve_fit to find the parameters that fit the test data.

    from scipy.optimize import curve_fit
    
    def fit_func(x, a0, b0, c0):
       a = a0 * x
       b = b0 * np.sin(x)
       Fx = np.array([F(t, ai, bi) for (ai, bi) in zip(a, b)])
       return c0*Fx
    
    p0 = [1, 1, 1] # initial guess for parameters
    popt, pcov = curve_fit(fit_func, x, y, p0)
    

    Here fit_func is a function that takes x, a0, b0, and c0 as input parameters and returns an array of fitted values for the test data x. p0 is an initial guess for the parameter values. popt is the optimal set of parameter values that minimizes the sum of the squares of residuals. pcov is the estimated covariance matrix of the parameter estimates.

  5. Plot the fit results.

    import matplotlib.pyplot as plt
    
    plt.plot(x, y, 'b', label='actual data')
    plt.plot(x, fit_func(x, *popt), 'r-', label='fit')
    plt.legend()
    plt.show()
    

This procedure should allow you to perform curve fitting for integral functions that have varying integration limits using Python.