Linear Regression

check_determ
domains
  int   = integer
  reals = real*
predicates
  lin_reg(reals,reals,real,real)
  sums(reals,reals,int,int,real,real,real,real,real,real,real,real)
clauses

/* lin_reg(Xs, Ys, M, C) is true if y = Mx + C is the best straight line   */
/*   fit for the given points (X, Y).                                      */
lin_reg(Xs, Ys, M, C):-
  sums(Xs, Ys, 0, N, 0, S_X, 0, S_Y, 0, S_XY, 0, S_XX),
  M = (S_X * S_Y / N - S_XY) / (S_X * S_X / N - S_XX),
  C = S_Y / N - M * S_X / N.

sums([], [], N, N, S_X, S_X, S_Y, S_Y, S_XY, S_XY, S_XX, S_XX).
sums([X|Xs], [Y|Ys], N0, N, S_X0, S_X, S_Y0, S_Y, S_XY0, S_XY, S_XX0, S_XX):-
  N1 = N0 + 1,
  S_X1 = S_X0 + X,
  S_Y1 = S_Y0 + Y,
  S_XY1 = S_XY0 + X * Y,
  S_XX1 = S_XX0 + X * X,
  sums(Xs, Ys, N1, N, S_X1, S_X, S_Y1, S_Y, S_XY1, S_XY, S_XX1, S_XX).

Turbo Prolog Index     Home Page