[comp.sys.handhelds] Least Squares Approximation

adkins@tortoise.cis.ohio-state.edu (Brian Adkins) (02/27/91)

The following is a program to perform a least squares fit on a set of 
data points.  The input is as follows:

level 3: a vector of x values ie.  [1 4 5 8 10 ...]
level 2: a vector of corresponding y values ie.  [3 4 5 7 6 ...]
level 3: a list of names of functions ie. {F1 F2 F3 ...}

The results are a user-defined function that approximates the data in 
level 2, and an error coefficient in level 1.  With the right choice of 
functions the program will do linear regression (I know it's already built
in!) or interpolating polynomials etc.  This is my first "real" program so
I'd rather you Email me for improvements etc. instead of blasting it on the
net.  Thanks.

Oh by the way, I typed this instead of uploading it so replace SQRT with
the square root key and THETA with alpha-right-shift F.

<<
  4 5 FOR I
    DUP SIZE EVAL I ROLLD I ROLLD
  NEXT
  5 ROLLD 0 0 0 0 0 -> X Y N F M THETA B A C PHI 
  <<
    1 M FOR I
      1 N FOR J
        'X(J)' EVAL 'F(I)' EVAL ->NUM
      NEXT
      N ->ARRY
    NEXT
    M ->LIST 'THETA' STO 
    1 M FOR I
      Y 'THETA(I)' EVAL DOT
    NEXT
    M ->ARRY 'B' STO 
    1 M FOR I
      1 M FOR J
        'THETA(J)' EVAL 'THETA(I)' EVAL DOT
      NEXT
    NEXT
    M DUP 2 ->LIST ->ARRY 'PHI' STO B PHI / 'C' STO
    'C(1)' EVAL { T } 'F(1)' EVAL APPLY EVAL *
    2 M FOR I
      'C(I)' EVAL { T } 'F(I)' EVAL APPLY EVAL * +
    NEXT
    ->STR 1 "=" REPL "'A(T)" SWAP + OBJ-> DEFINE
    'A(X(1))-Y(1)' ->NUM SQ
    2 N FOR I
      'A(X(I))-Y(I)' ->NUM SQ +
    NEXT
    N / SQRT 'A' RCL SWAP
  >>
>>

adkins@europa.cis.ohio-state.edu (Brian Adkins) (02/28/91)

Oops! I forgot to mention an important detail concerning the least squares
program I posted.  The list of functions must be linearly independant.

Brian Adkins