Search code examples
pythonscipyleast-squares

Scipy LeastSq errorbars


I'm fitting an experimental spectrum to a theoretical expectation using LeastSq from SciPy. There are of course errors associated with the experimental values. How can I feed these to the LeastSq or do I need a different routine? I find nothing in the documentation.


Solution

  • The scipy.optimize.leastsq function does not have a built-in way to incorporate weights. However, the scipy.optimize.curve_fit function does have a sigma parameter which can be used to indicate the variance of each y-data point.

    curve_fit uses 1.0/sigma as the weight, where sigma can be an array of length N, (the same length as ydata).

    So somehow you have to surmise the variance of each ydata point based on the size of the error bar and use that to determine sigma.

    For example, if you declare that half the length of the error bar represents 1 standard deviation, then the variance (what curve_fit calls sigma) would be the square of the standard deviation.

    sigma = (length_of_error_bar/2)**2
    

    Reference: