DEFDBL a-z
DECLARE FUNCTION f (x)
DECLARE FUNCTION dfdx (x)
'
' Sample program to search a zero of a non linear
' function f(x)
' The function is placed in FUNCTION f, and its first
' derivative in FUNCTION dfdx
'
' Input for this program are :
'
' An initial guess in the neighborhood of the solution
' to start the iteration
'
' A maximum number of iterations allowed
'
' A small number epsilon (for instance 0.0001), expressing
' the criterion of convergence. When two successive itera-
' tions are closer to each other than epsilon, the last
' iteration is considered as the correct solution
'
'
PRINT ""
PRINT "P. Hellings: Astrophysics with a PC : SOME NUMERICAL METHODS"
PRINT "-------------------------------"
' Adapted by Kiyoshi Kawabata from the programs of Chapter 1
' on May 31, 2008
PRINT "Newton-Raphson method to find zeros of a given f(x)=0
PRINT " Sample function on P.20: f(x)=exp(x)-6x"
COLOR 14
PRINT " Try (1)x=0.0, maxiter%=10, epsilon=1.E-7"
PRINT " (2)x=3.0, maxiter%=10, epsilon=1.E-7
COLOR 15
INPUT "Initial guess of the zero : "; x
INPUT "Maximum number of iteration allowed : "; maxiter%
INPUT "Convergence criterion epsilon : "; epsilon
iter% = 0
DO
' save previous approximation for use in convergence test
xold = x
' compute new approximation
x = x - f(x) / dfdx(x)
' update number of iterations
iter% = iter% + 1
PRINT USING "### #####.#########"; iter%; x
LOOP UNTIL (iter% > maxiter%) OR (ABS(x - xold) < epsilon)
IF iter% > maxiter% THEN
PRINT "Maximum number of iterations used"
ELSE
PRINT "method has converged: x = "; x
END IF
PRINT ""
COLOR 14
PRINT "Program terminated. Press any key"
DO
LOOP WHILE INKEY$ = ""
END
FUNCTION dfdx (x)
'
' contains the first derivative of the function f(x)
'
dfdx = EXP(x) - 6
END FUNCTION
FUNCTION f (x)
'
' contains the function for which z zero is searched for
f = EXP(x) - 6 * x
END FUNCTION