c PROGRAM TO FIND A ROOT OF f(x) = 0 USING VANILLA NEWTON's METHOD
program newt
implicit none
real xold,tol
real xnew
real ff,ffprime,fold,fpold
integer iter,itstart,itend
external ff, ffprime
c THE INITIAL GUESS FOR THE ROOT IS xold
c FIND ROOT TO WITHIN A TOLERANCE tol
c THE FUNCTIONS f(x),f'(x) ARE DEFINED IN A SUBROUTINES GIVING ff,ffprime
c DO A MAXIMUM OF itend ITERATIONS
itstart=1
itend=50
c ENTER INITIAL GUESS, called xold, and TOL
c IF |ff(xold)| < tol THEN xold IS A GOOD APPROXIMATION OF THE ROOT
C MAIN ITERATION LOOP
do iter=itstart,itend
c DEFINE f(xold) and f'(xold)
c AVOID DIVIDING BY 0
c GET THE NEW ITERATE xnew BY THE NEWTON FORMULA
c CHECK IF ff(xnew) IS A ROOT
c PUT xold INTO xnew
enddo
999 stop
end
c****6****************************************************************72
real function ff(x)
c THIS FUNCTION SUBROUTINE COMPUTES THE VALUE OF f AT A POINT x
c DEFINE ff
return
end
c****6****************************************************************72
real function ffprime(x)
c THIS FUNCTION SUBROUTINE COMPUTES THE VALUE OF f' AT A POINT x
c DEFINE ffprime
return
end
/subsectionFinding f' Newton's method requires a formula for both f(x) and f'(x). It is sometimes true that we can figure out how to evaluate the function f whose root(s) we wish to find, but may be unable to determine f'. To use Newton's method, we need to figure out how to evaluate f', and here we present two possible approaches.
Substituting this into Newton's method gives the Secant method.
For good accuracy,
should be about
.
In either case, one must be careful - the approximations both involve
taking the ratio of two numbers which are small in magnitude, and such a
division is prone inaccuracies. You should try using finite differences
to approximate f' with various values of
, in both single and
double precision.