Mirror

Least squares line fitting in Delphi (Views: 707)


Problem/Question/Abstract:

Least squares line fitting in Delphi

Answer:

Example that finds least squares fit for y = Mx + c

procedure LeastSquares(X, Y: array of Extended; var M: Extended; var C: Extended);
var
  SumX, SumY, SumX2, SumXY: Extended;
  n, i: Integer;
begin
  if High(X) <> High(Y) then
    raise
      Exception.Create('LeastSquares() Error - Input X & Y arrays must be
                         of the same length');
  n := High(X) + 1;
  SumX := 0.0;
  SumY := 0.0;
  SumX2 := 0.0;
  SumXY := 0.0;
  for i := 0 to n - 1 do
  begin
    SumX := SumX + X[i];
    SumY := SumY + Y[i];
    SumX2 := SumX2 + (X[i] * X[i]);
    SumXY := SumXY + (X[i] * Y[i]);
  end;
  if (n * SumX2) = (SumX * SumX) then
    raise Exception.Create('LeastSquares() Error - X Values cannot all be the same');
  M := ((SumY * SumX2) - (SumX * SumXY)) / ((n * SumX2) - (SumX * SumX));
  C := ((n * SumXY) - (SumX * SumY)) / ((n * SumX2) - (SumX * SumX));
end;

<< Back to main page