home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / forth / compiler / fpc / source / l3p130.seq < prev    next >
Encoding:
Text File  |  1990-04-01  |  1.3 KB  |  54 lines

  1. COMMENT:
  2. Finding a square root by Newton's Method.  Have you studied any Calculus
  3. lately?
  4.  
  5. Theory:  Let  f(x) = x^2 - n  where the root or zero of this
  6. function is the square root of n.
  7.  
  8. Newton's Method:   use guess xo to get better guess xn
  9. according to:   xn = xo - f(xo)/f'(xo)
  10.  
  11. It can be shown that:  xn = ( xo + n/xo )/2
  12. COMMENT;
  13. \ Here is the square root program.
  14. : XNEW  ( n xold -- n xnew )
  15.         2DUP  /  +  2/  ;
  16.  
  17. : SQRT  ( n -- root )
  18.         DUP 0< IF ABORT" Illegal argument" THEN
  19.         DUP 1 >
  20.         IF    DUP 2/  ( n  n/2 )
  21.         10 0 DO XNEW LOOP NIP     \ I say.. about 10 time should do it.
  22.         THEN  ;
  23.  
  24. COMMENT:
  25. Note:  This is not the best or fastest square root algorithm.
  26.  
  27. Here is a simple program that will help you test the square root
  28. program.
  29. COMMENT;
  30.  
  31. \ Hypotenuse of a right triangle.
  32. : HYPO  ( a b --  c )
  33.         DUP * SWAP
  34.         DUP * +
  35.         SQRT  ;
  36. : TEST  ( -- )
  37.         15 1 DO  15 1 DO
  38.         CR I J 2DUP  4 .R 4 .R  HYPO 4 .R
  39.         LOOP KEY DROP CR LOOP ;
  40.  
  41.  
  42. \ Here is the solution to problem 3.28 of Lesson 2 Part 12
  43.  
  44.  
  45. : AVERAGE  ( x1 f1 x2 f2 ... xn fn    -- )
  46.         0 0 DEPTH  2/ 1-  0
  47.         ?DO  2 PICK +
  48.              2SWAP *
  49.              ROT  +  SWAP
  50.         LOOP
  51.         CR ." The average of the "
  52.         DUP .   ." numbers is "  / . CR ;
  53.  
  54.