Newton's Method (Fortran)
Root Finding
Newton's method (also known as the Newton-Raphson method) is an iterative root-finding algorithm. This Fortran implementation demonstrates the method for finding roots of a function.
Newton's Method
Given a function , Newton's method finds a root by iterating:
The method converges quadratically when the initial guess is sufficiently close to the root.
Implementation
This implementation finds the root of , which has roots at .
!https://en.wikipedia.org/wiki/Newton%27s_method
program newton_method
implicit none
integer, parameter:: dp=kind(0.d0) ! double precision
real(dp) :: f_val, f_prime_val, epsilon, tol, x0, x1
integer :: max_iter, i
max_iter = 1000
tol = 0.001
x0 = 4.0_dp
epsilon = 0.00001_dp
do i = 1,max_iter
f_val = f(x0)
f_prime_val = f_prime(x0)
if (abs(f_prime_val) < epsilon) then
exit
end if
x1 = x0 - f_val/f_prime_val
if (abs(x1-x0) <= tol) then
print *, x1
exit
end if
x0 = x1
end do
contains
function f(x)
real(dp) :: f
real(dp) :: x
f = x**2 - 4
end function f
function f_prime(x)
real(dp) :: f_prime
real(dp) :: x
f_prime = 2*x
end function f_prime
end program newton_method Key Features
- Uses double precision for numerical accuracy
- Checks for division by zero (when )
- Convergence check based on tolerance
- Maximum iteration limit to prevent infinite loops
- Uses
containsto define internal functions
Output
For the initial guess , the method converges to :
2.0000000000000000 Trace it by hand
Newton's iteration: . With and , this simplifies to .
- , error .
- , error .
- , error .
The error squares each iteration — quadratic convergence. Going from to to matches the doubling of correct digits per step. After 5 iterations you're already at full double-precision accuracy (). Compare with bisection, which only halves the error per iteration: it takes ~50 bisection steps to reach what 5 Newton steps gives you.
The catch: Newton requires a derivative, can diverge from a bad starting point, and oscillates near critical points where . Bisection always converges from a sign-change bracket but is linear, not quadratic.