#! /usr/bin/env python ## to run and view the results, do this: ## $ python lsq.py > lin-out ## $ gnuplot ## gnuplot> plot 'linear.dat' with linespoints ## gnuplot> replot 'lin-out' with linespoints import string def __main__(): sum_x = 0 sum_x2 = 0 sum_y = 0 sum_xy = 0 N = 0 lines = open('linear.dat').readlines() for line in lines: fwords = map(float, string.split(line)) sum_x += fwords[0] sum_y += fwords[1] sum_x2 += fwords[0]*fwords[0] sum_xy += fwords[0]*fwords[1] N += 1 m = (sum_y*sum_x/N - sum_xy)/(sum_x*sum_x/N - sum_x2) b = (sum_y - m*sum_x)/N print '## line equation is y = m * x + b =', m, '* x + (', b, ')' for i in range(120): x = i/5.0 print x, m*x + b __main__()