Least-Squares Fit to a Straight Line python code

Simplest if you just want a line is scipy.stats.linregress:

from scipy import stats
slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)

Link to docs


If I understand your question correctly, you have two datasets x and y where you want to perform a least square fit.

You don't have to write the algorithm yourself, curve_fit from scipy.optimize should do what you want, try:

from scipy.optimize import curve_fit

def f(x, A, B): # this is your 'straight line' y=f(x)
    return A*x + B

popt, pcov = curve_fit(f, x, y) # your data x, y to fit

where popt[0], popt[1] would be the slope and intercept of the straight line.

For more details and examples, see: http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html#scipy.optimize.curve_fit

Tags:

Python

Plot