Author: Jonas Bilinkevicius Least squares line fitting in Delphi Answer: Example that finds least squares fit for y = Mx + c 1 2 procedure LeastSquares(X, Y: array of Extended; var M: Extended; var C: Extended); 3 var 4 SumX, SumY, SumX2, SumXY: Extended; 5 n, i: Integer; 6 begin 7 if High(X) <> High(Y) then 8 raise 9 Exception.Create('LeastSquares() Error - Input X & Y arrays must be 10 of the same length' 11 n := High(X) + 1; 12 SumX := 0.0; 13 SumY := 0.0; 14 SumX2 := 0.0; 15 SumXY := 0.0; 16 for i := 0 to n - 1 do 17 begin 18 SumX := SumX + X[i]; 19 SumY := SumY + Y[i]; 20 SumX2 := SumX2 + (X[i] * X[i]); 21 SumXY := SumXY + (X[i] * Y[i]); 22 end; 23 if (n * SumX2) = (SumX * SumX) then 24 raise Exception.Create('LeastSquares() Error - X Values cannot all be the 25 same' 26 M := ((SumY * SumX2) - (SumX * SumXY)) / ((n * SumX2) - (SumX * SumX)); 27 C := ((n * SumXY) - (SumX * SumY)) / ((n * SumX2) - (SumX * SumX)); 28 end;