home *** CD-ROM | disk | FTP | other *** search
- COMMENT:
- Finding a square root by Newton's Method. Have you studied any Calculus
- lately?
-
- Theory: Let f(x) = x^2 - n where the root or zero of this
- function is the square root of n.
-
- Newton's Method: use guess xo to get better guess xn
- according to: xn = xo - f(xo)/f'(xo)
-
- It can be shown that: xn = ( xo + n/xo )/2
- COMMENT;
- \ Here is the square root program.
- : XNEW ( n xold -- n xnew )
- 2DUP / + 2/ ;
-
- : SQRT ( n -- root )
- DUP 0< IF ABORT" Illegal argument" THEN
- DUP 1 >
- IF DUP 2/ ( n n/2 )
- 10 0 DO XNEW LOOP NIP \ I say.. about 10 time should do it.
- THEN ;
-
- COMMENT:
- Note: This is not the best or fastest square root algorithm.
-
- Here is a simple program that will help you test the square root
- program.
- COMMENT;
-
- \ Hypotenuse of a right triangle.
- : HYPO ( a b -- c )
- DUP * SWAP
- DUP * +
- SQRT ;
- : TEST ( -- )
- 15 1 DO 15 1 DO
- CR I J 2DUP 4 .R 4 .R HYPO 4 .R
- LOOP KEY DROP CR LOOP ;
-
-
- \ Here is the solution to problem 3.28 of Lesson 2 Part 12
-
-
- : AVERAGE ( x1 f1 x2 f2 ... xn fn -- )
- 0 0 DEPTH 2/ 1- 0
- ?DO 2 PICK +
- 2SWAP *
- ROT + SWAP
- LOOP
- CR ." The average of the "
- DUP . ." numbers is " / . CR ;
-
-