[SciPy-user] Simple least-squares curve fitting example

James R. Phillips scipy at zunzun.com
Sat Jan 3 15:53:11 CST 2004


Here is a linear least squares curvefitting example
for the distribution if you would like to use it.

     James Phillips
     http://zunzun.com


import scipy.linalg.basic

xdata = [5.357, 5.457, 5.797, 5.936, 6.161, 6.697, 6.731, 6.775, 8.442, 9.769, 9.861]
ydata = [0.376, 0.489, 0.874, 1.049, 1.327, 2.054, 2.077, 2.138, 4.744, 7.068, 7.104]
matrix = []

for x in xdata:
    matrix.append([1.0, x, x*x]) # for y = a + bx + cx^2

coeffs = scipy.linalg.basic.lstsq(matrix, ydata)[0]

print "scipy.linalg.basic.lstsq curve fitting example"
print "fitting data to quadratic equation y = a + bx + cx^2"

print "yields:  x data     y data    calc value   error"
for i in range(len(xdata)):
    ycalc = coeffs[0] + coeffs[1] * xdata[i] + coeffs[2] * xdata[i] * xdata[i]
    error = ycalc - ydata[i]
    print "         % .3f    % .3f      % .3f    % .3f" % (xdata[i], ydata[i], ycalc, error)
print



More information about the SciPy-user mailing list