From: Fredrik Viklund <fv@LINK.Physchem.KTH.SE>
Subject:  v04i028:  bfit_fv - Flexible Least Square Fit v1.2, Part01/01
Newsgroups: comp.sources.hp48
Organization: Royal Institute of Technology, Stockholm
Followup-To: comp.sys.hp48
Approved: spell@seq.uncwil.edu

Checksum: 3297968093 (verify with brik -cv)
Submitted-by: Fredrik Viklund <fv@LINK.Physchem.KTH.SE>
Posting-number: Volume 4, Issue 28
Archive-name: bfit_fv/part01

BEGIN_DOC bfit.doc

Abstract:
~~~~~~~~~
        Best Fit 1.2 is a user RPL-program that least-square-fits
        a function to data points stored in SIGMADAT.
        Best Fit 1.2 makes it easy to fit a (customized)
        polynomial. It is possible to fit any function (with
        some restrictions) to data.

Features:
~~~~~~~~~
    o Userdefined function least square fit
    o Simplified plots
    o Easy to customize to fit your needs


Preface:
~~~~~~~~
Some time ago I wanted to fit a polynomial to some data. I then realized
that HP hadn't included that possibility in the '48. As I had some time
to spend, I wrote a simple routine that could fit a
polynom to a set of data. As this was my first "more-than-5-
lines-program"-project I changed it over and over again to see if I
could use some more predefined functions from the manuals... (Mostly,
the changes were made sitting in a bus on my way to school!)


Copyright:
~~~~~~~~~~
This program and documentation is (c) march 1992 Fredrik Viklund. If you
find it worthwile to use this program you have my permission to change
it on one condition! If you make any changes you have to change the
first line in ABOUT to "Modified Best Fit" and the version number to
"1.2m". If you distribute this program, please include the whole
unmodified directory and this documentation.



Disclaimer:
~~~~~~~~~~~
By using this program or reading more of this document I, the reader or
user agrees that the author, Fredrik Viklund has no responsibility
whatever of the results of the use of this program.


Introstructions:
~~~~~~~~~~~~~~~~
1. Download BFIT12 to your HP48
2. Press BFIT - a menu appears
(3. Press softkey 1 (A) to go to STAT menus, enter data in SIGMADAT, or
    enter matrix and stor in SIGMADAT by pressing leftshift SIGMADAT.
    There already are some data stored, so you don't have to enter data
    right now. Then press right-shift SIGMADAT (softkey 1) to display
    SIGMADAT)
4. Press FIT to fit data to function
5. Enter how many terms you want in your expression. Note that there
   are three terms in a second degree polynomial (including a constant).
6. Press right-shift FIT to see matrix of least square fitted
   coefficients.
7. Press ->EQ to make a readable equation of the coefficients. Press
   right-shift ->EQ to see EQ were it is now stored. (Left-shift ->EQ
   will store expression in level 1 in EQ.)
8. Press SCATR to make a scatterplot of data.
9. Press ATTN to return to plot menu.
10. Press FUNC to plot fitted function EQ.
11. Press ATTN to return to plot menu.
12. Press EXIT to return to main menu.
13. Press ABOUT to see name, version, copyright, my name and adress.
14. If you still reads this, press ATTN to leave ABOUT, then press OPERS
    and EDIT.
15. Add \<< ln \>> as the 4th element (between \<< 2 ^ \>> and
    \<< 3 ^ \>> ) and exit EDIT by pressing ENTER
16. Store new operators in OPER by pressing right-shift OPERS
17. Repeat steps 4 to 10 (use 4 or more terms in step 5)
18. Note the differences, and that EQ now contains a 'ln'-term.


Additional notes:
~~~~~~~~~~~~~~~~~
In menus: SCATR erases PICT and makes a autoscaled scatterplot
    rightshifted SCATR plots data "as is"
    FUNC plots function on current PICT (no ERASE)

It is not possible to fit such things as c1*SIN(c2*X) due to the method.
Only expressions like c*SIN(X) will work. (I think...)
These more spectacular functions may have their value if you want to fit
a smooth curve to you scatter.

Perhaps there are some undocumented features, but I leave that for you
to find out. I have already written too much...


Feed-Back:
~~~~~~~~~~
I would really appreciate if you let me know if you need, use or delete
this program. 

+------------------------------------------------------+
| Fredrik Viklund                   FV@Chemstud.KTH.SE |
| Bussvaegen 5                                         |
| S-132 43  SALTSJO-BOO                                |
| SWEDEN                                               |
+------------------------------------------------------+


O  /
 \/
 /\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O  \


END_DOC

BEGIN_RPL bfit.rpl
%%HP: T(3)A(R)F(.);
DIR
  BFIT                      @ Kind of a shell
    \<< { { "\GSDAT" {      @ 1st key
      \<< 40 MENU           @ normal: goto STAT-menu
      \>>                   @
      \<< STO\GS            @ lshift: STO in \SIGMA-DAT
      \>>                   @
      \<< RCL\GS            @ rshift: RCL \SIGMA-DAT
      \>> } } { "FIT"       @ 2nd key
{                           @
      \<<                   @
"Number of terms
in expression:"
"" INPUT OBJ\-> FIT         @ normal: prompt and run FIT
      \>>                   @
      \<<                   @ lshift: NOOP
      \>>                   @
      \<< RESULT            @ rshift: display RESULT
      \>> } } {             @
"OPERS" {                   @ 3rd key
      \<< OPERS             @
      \>>                   @
      \<< 'OPERS' STO       @ normal: STO object in variable OPERS
      \>> } } { "\->EQ"     @ 4th key
{ \->EQ                     @ normal: make EQ from REUSLT
      \<< 'EQ' STO          @ lshift: STO object in EQ
      \>> EQ } } {          @ rshift: recall EQ
"PLOT" {                    @ 5th key (with submenu)
      \<< { { "ERASE"       @ 1st key: erase PICT
{ ERASE } } {               @
"SCATT" {                   @ 2nd key: scatter \SIGMA-DAT
        \<< SCATRPLOT       @
GRAPH                       @
        \>>                 @
        \<< SCATTER         @
DRAW GRAPH                  @
        \>> } } {           @
"FUNC"                      @ 3rd key: draw EQ
        \<< FUNCTION        @
DRAX DRAW GRAPH             @
        \>> } "" {          @ 4th key: NOOP
"EXIT" BFIT } }             @ 5th key: return to main menu
TMENU                       @
      \>> } } {             @
"ABOUT" { ABOUT } }         @ 6th key: ABOUT BFIT
} TMENU                     @
    \>>                     @
  OPERS {                   @ Sample variable OPERS
    \<< 0 ^                 @ Contains the functions that form
    \>>                     @ EQ.
    \<< 1 ^                 @
    \>>                     @ In this case the first three terms
    \<< 2 ^                 @ will be X raised to 0, 1 and 2. Then
    \>>                     @ SIN, EXP and 1/X -terms will be added.
    \<< 3 ^                 @
    \>>                     @ If you omitt OPERS, FIT will make a
    \<< 4 ^                 @ "pure" polynomial (X raised to 0, 1, 2
    \>>                     @ etc). Also if you specify 3 elements in
    \<< 5 ^                 @ OPERS and a 6 element-expression, FIT
    \>>                     @ will use the three specified expressions
    \<< SIN                 @ and then add X^(element number)
    \>>                     @
    \<< TAN                 @ If you want to fit c0+c1*X^0.5+c2*X
    \>>                     @ OPERS would be:
    \<< 8 ^                 @ { \<< 0 ^ \>> \<< 0.5 ^ \>> \<< 1 ^ \>> }
    \>>                     @
    \<< 9 ^                 @
    \>>                     @
    \<< 10 ^                @
    \>> }                   @
  FIT                       @ "Main" program
    \<< \-> TERMS           @ Get number of terms from level 1
      \<< BFPAR 1           @ Store in 1st pos of PFPAR
TERMS PUT 'BFPAR'           @
STO                         @
        IF \GSDAT           @ Check if \SIGMA-DAT is matrix (real
TYPE 3 \=/ \GSDAT TYPE      @ or complex).
4 \=/ AND                   @
        THEN # 601h         @
DOERR                       @ Else "Invalid \SIGMA Data"
        END \GSPAR 2        @ Get independent data column from \SIGMA-PAR
        IFERR GET           @ If \SIGMA-PAR does not exist: create
        THEN { 1 2          @
0 0 LINFIT } '\GSPAR'       @
STO GET                     @
        END \GSPAR 1        @
GET \-> YCOLU XCOLU         @ Store columns in YCOLU and XCOLU
        \<< TERMS           @
\GSDAT SIZE OBJ\-> DROP     @
DROP \-> JSIZE ISIZE        @ Store dimensions of Vandermonde matrix
          \<< 1 ISIZE       @ as ISIZE and JSIZE
            FOR I           @
\GSDAT { I XCOLU }          @
GET \-> XI                  @ Get one element at a time. STO as Xi
              \<< 0         @
TERMS 1 -                   @ Execute the right OPERS-operation
FOR J XI                    @ or raise to its j-th power
  IFERR OPERS J 1 +         @
GET EVAL                    @
  THEN DROP DROP J          @
^                           @
  END                       @
NEXT                        @
              \>>           @
            NEXT {          @
ISIZE JSIZE } \->ARRY       @ When finished with all elements:
1 ISIZE                     @ make array (Vandermonde matrix)
            FOR I           @
\GSDAT { I YCOLU }          @ Extract dependent data from Y-column
GET                         @ of \SIGMA-DAT
            NEXT {          @
ISIZE 1 } \->ARRY           @
          \>> \-> XDAT      @ Store as XDAT and YDAT
YDAT                        @
          \<< XDAT          @ Calculation:
TRN YDAT * XDAT TRN         @ TRN(X)*X*c = TRN(X)*Y
XDAT * \-> Y X              @ c is the least-square-fitted coefficients
            \<< Y X /       @ in matrix format
Y X 3 PICK RSD X /          @ Increase precision
+                           @
            \>>             @
'RESULT' STO                @ Store c in RESULT variable
          \>>               @
        \>>                 @
      \>>                   @
    \>>                     @
  RESULT                    @
[[ 1.00000006486 ]          @
 [ .999999927664 ]          @
 [ 1.00000000666 ]          @
 [ 1.00000008129 ]]         @
  \->EQ                     @
    \<< -3 FS?              @
      IFERR PPAR 3          @ Make EQ-program
GET PPAR 7 GET              @ Symbolic evaluation set?
      THEN DROP             @ Get independent and dependent variables
DROP 'X' 'Y'                @ If nonexistant: assume 'X' and 'Y'
      END BFPAR 1           @
GET \-> FLAG3 INDVAR        @
DEPVAR TERMS                @
      \<< -3 CF             @ Store as FLAG3, INDVAR and DEPVAR
RESULT OBJ\-> DROP          @
TERMS 1                     @ Set symbolic evaluation
        FOR K               @ Some magic performed on RESULT
INDVAR                      @ Principle: perform OPERS on INDEP,
          IFERR             @ multiply with coefficient and add
OPERS K GET EVAL            @ together
          THEN DROP         @
DROP K 1 - ^                @
          END * K           @
ROLLD -1                    @
        STEP 1              @
TERMS 1 -                   @
        FOR K SWAP          @
+                           @
        NEXT 'EQ'           @
STO                         @
        IF FLAG3 1          @
==                          @ Store in EQ
        THEN -3 SF          @ Restore flag -3 as found earlier
        END                 @
      \>>                   @
    \>>                     @
  EQ '1.00000006486         @ Sample Equation
+.999999927664*X+           @
1.00000000666*X^2+          @
1.00000008129*LN(X)         @
'                           @
  \GSDAT                    @ Sample \SIGMA-DAT
[[ 1 -7 ]		    @
 [ 2 -33.5342640972 ]	    @
 [ 3 -83.5069385566 ]	    @
 [ 4 -156.068528194 ]	    @
 [ 5 -250.952810438 ]	    @
 [ 6 -368.041202654 ]]	    @
  \GSPAR { 1 2 0 0          @ Sample \SIGMA-PAR
LINFIT }                    @
  PPAR {                    @ Sample PPAR
(1,-1.44141568686)          @
(5,32.6094379124) X         @
0 (0,0) FUNCTION Y          @
}                           @
  BFPAR { 4 }               @ Sample BFPAR (contains number of terms)
  ABOUT                     @ About BFIT
    \<< CLLCD               @
"       Best Fit" 1         @
DISP                        @
"    ver 1.2  \169 1992"    @
3 DISP                      @
"   Fredrik  Viklund"       @
5 DISP                      @
"  FV@Chemstud.KTH.SE"      @
7 DISP 7 FREEZE             @
    \>>                     @
END                         @


END_RPL
