Best Linear Fit to a List of Points


Ken Levasseur , UMass Lowell

Instructions

1. Enter the points to which you would like to fit a line in the form indicated by the example that is provided.
2. Press this button:

Do this in Mathematica

The Mathematica function Fit does the real work here. If you have a list of ordered pairs called data, each pair enclosed in { }'s as a list, then Fit[data,{1,x},x] will determine the equation of the line of best fit as a function of x. The rest of the code you see below takes care of presenting a nice graph with points and line of best fit.

Here is how you can get this graph in Mathematica, with information on the best fit line displayed a bit differently than in this page.



data={{0,0},{1,1},{2,3}};

If[ListQ[data]&&(Length[data]>2),
      y=Fit[data,{x,1},x];
      {xmin,xmax}={Min[#],Max[#]}&[First[Transpose[data]]];
      {ymin,ymax}={Min[#],Max[#]}&[Join[Last[Transpose[data]],{y/.{x->xmin},y/.{x->xmax}}]];
      Plot[y, {x,xmin,xmax},Epilog->Map[Point,data]];
      y,
      Graphics[{Text["Bad input",{0,0}]}
      ] 

 

Ken Levasseur
Mathematical Sciences
UMass Lowell
Kenneth_Levasseur@uml.edu
Ken's WebMathematica Scripts