-- "linear regression" fit x,y data to a line
-- See Also: XFun "linfit"
-- uses := to avoid re-calculating sums
sumx := sum(x[i],i,1,n):
sumxx:= sum(x[i]^2,i,1,n):
sumy := sum(y[i],i,1,n):
sumyy:= sum(y[i]^2,i,1,n):
sumxy:= sum(x[i]*y[i],i,1,n):

Sxx=n*sumxx-sumx^2
Sxy=n*sumxy-sumx*sumy

slope=Sxy/Sxx
intercept=(sumxx*sumy-sumx*sumxy)/(n*sumxx-sumx^2)
correlation=Sxy/sqrt(Sxx*(n*sumyy-sumy^2))

-- user must supply a data file of x y values.
data=read("xydata")
n=count(data)   -- number of data points

-- file is organized as x,y pairs. 
x[i]=data[i,1] dim[n] -- Make sep x and y arrays
y[i]=data[i,2] dim[n]

plot data                -- plot data points
plot X*slope+intercept   -- plot best fit line

label slope:0.720
label intercept:-1.122
label correlation:0.973

-- Note: can also be used to do 2 param fit for other functions.
~
 f(x) = -cos(x)
 plot f(X)*slope+intercept
 x[i]=f(data[i,1]) dim[n]
~
