Fortran Root Finding
Many scientific questions reduce to solving an equation f(x) = 0: the angle at which a projectile hits a target, the interest rate of a loan, the energy levels of a quantum well. Unless f is very simple, there is no formula; instead we use iterative root-finding methods. This lesson implements the three classic ones: bisection, Newton's method and the secant method.
Our test equation is x**3 - 2*x - 5 = 0, which has one real root near 2.0946.
Bisection
If f is continuous and f(a) and f(b) have opposite signs, there is a root between them. Bisection repeatedly halves the interval, keeping the half where the sign change is. It's slow but can't fail:
module roots
use iso_fortran_env, only: dp => real64
implicit none
contains
pure function f(x) result(y)
real(dp), intent(in) :: x
real(dp) :: y
y = x**3 - 2.0_dp * x - 5.0_dp
end function f
subroutine bisection(a_in, b_in, tol, root, iterations)
real(dp), intent(in) :: a_in, b_in, tol
real(dp), intent(out) :: root
integer, intent(out) :: iterations
real(dp) :: a, b, m
a = a_in
b = b_in
if (f(a) * f(b) > 0.0_dp) error stop 'bisection: f(a) and f(b) must differ in sign'
iterations = 0
do while (b - a > tol)
m = 0.5_dp * (a + b)
if (sign(1.0_dp, f(m)) == sign(1.0_dp, f(a))) then
a = m
else
b = m
end if
iterations = iterations + 1
end do
root = 0.5_dp * (a + b)
end subroutine bisection
end module roots
program bisect_demo
use roots
implicit none
real(dp) :: r
integer :: n
call bisection(2.0_dp, 3.0_dp, 1.0e-12_dp, r, n)
print '(a, f16.12)', 'root = ', r
print '(a, es10.2)', 'f(root) = ', f(r)
print '(a, i0)', 'iterations: ', n
end program bisect_demoroot = 2.094551481543
f(root) = 2.68E-12
iterations: 40
Each step gains one binary digit, so 40 steps shrink the interval from 1 to about 10⁻¹². Comparing signs with sign(1.0_dp, …) instead of testing f(a) * f(m) > 0 avoids overflow when the function values are huge.
Newton's method
Newton's method follows the tangent line: x ← x − f(x)/f′(x). Near a simple root the number of correct digits roughly doubles each step (quadratic convergence), but it needs the derivative and a good starting point.
program newton_demo
use iso_fortran_env, only: dp => real64
implicit none
real(dp) :: x, dx
integer :: k
x = 2.0_dp
do k = 1, 20
dx = f(x) / df(x)
x = x - dx
print '(a, i2, a, f20.16, a, es9.2)', 'step', k, ': x =', x, ' |dx| =', abs(dx)
if (abs(dx) < 1.0e-14_dp * abs(x)) exit
end do
contains
pure real(dp) function f(x)
real(dp), intent(in) :: x
f = x**3 - 2.0_dp * x - 5.0_dp
end function f
pure real(dp) function df(x)
real(dp), intent(in) :: x
df = 3.0_dp * x**2 - 2.0_dp
end function df
end program newton_demostep 1: x = 2.1000000000000001 |dx| = 1.00E-01
step 2: x = 2.0945681211041851 |dx| = 5.43E-03
step 3: x = 2.0945514816981992 |dx| = 1.66E-05
step 4: x = 2.0945514815423265 |dx| = 1.56E-10
step 5: x = 2.0945514815423265 |dx| = 7.96E-17
The step sizes 10⁻¹, 10⁻³, 10⁻⁵, 10⁻¹⁰, 10⁻¹⁷ show the doubling of correct digits. The stopping test is relative (1e-14 * abs(x)), so it works for roots of any magnitude.
Note: Newton's method can diverge or cycle when started far from the root or near a point where f′(x) ≈ 0. Robust solvers combine it with bisection: take a Newton step when it stays inside the bracketing interval, and bisect otherwise.
The secant method
When the derivative is unavailable, approximate it from the last two iterates. The secant method converges almost as fast as Newton (order ≈ 1.618, the golden ratio):
program secant_demo
use iso_fortran_env, only: dp => real64
implicit none
real(dp) :: x0, x1, x2
integer :: k
x0 = 2.0_dp
x1 = 3.0_dp
do k = 1, 50
x2 = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0))
print '(a, i2, a, f20.16)', 'step', k, ': x =', x2
if (abs(x2 - x1) < 1.0e-14_dp * abs(x2)) exit
x0 = x1
x1 = x2
end do
contains
pure real(dp) function f(x)
real(dp), intent(in) :: x
f = x**3 - 2.0_dp * x - 5.0_dp
end function f
end program secant_demostep 1: x = 2.0588235294117645
step 2: x = 2.0812636598450229
step 3: x = 2.0948241460940524
step 4: x = 2.0945494310352473
step 5: x = 2.0945514812275992
step 6: x = 2.0945514815423270
step 7: x = 2.0945514815423265
A reusable solver with a function argument
Finally, a general bisection-based solver that accepts any function, used here to find where cos(x) = x and the interest rate of a loan:
module solver
use iso_fortran_env, only: dp => real64
implicit none
abstract interface
function scalar_fn(x) result(y)
import :: dp
real(dp), intent(in) :: x
real(dp) :: y
end function scalar_fn
end interface
contains
function find_root(f, a_in, b_in, tol) result(root)
procedure(scalar_fn) :: f
real(dp), intent(in) :: a_in, b_in, tol
real(dp) :: root, a, b, fa, m, fm
a = a_in
b = b_in
fa = f(a)
do while (b - a > tol)
m = 0.5_dp * (a + b)
fm = f(m)
if ((fm > 0.0_dp) .eqv. (fa > 0.0_dp)) then
a = m
fa = fm
else
b = m
end if
end do
root = 0.5_dp * (a + b)
end function find_root
end module solver
program applications
use solver
implicit none
real(dp) :: x, r
x = find_root(cos_minus_x, 0.0_dp, 1.0_dp, 1.0e-12_dp)
print '(a, f14.10)', 'cos(x) = x at x = ', x
! a 200000 loan repaid with 360 monthly payments of 1199.10: what is the monthly rate?
r = find_root(loan_balance, 1.0e-6_dp, 0.05_dp, 1.0e-12_dp)
print '(a, f8.4, a)', 'annual interest rate: ', 12 * 100 * r, ' %'
contains
function cos_minus_x(x) result(y)
real(dp), intent(in) :: x
real(dp) :: y
y = cos(x) - x
end function cos_minus_x
function loan_balance(r) result(y) ! payment formula minus actual payment
real(dp), intent(in) :: r
real(dp) :: y
y = 200000.0_dp * r / (1.0_dp - (1.0_dp + r)**(-360)) - 1199.10_dp
end function loan_balance
end program applicationscos(x) = x at x = 0.7390851332
annual interest rate: 6.0000 %
Internal procedures can be passed as actual arguments (since Fortran 2008), which is handy for quick one-off functions like these.
Test yourself
What condition does bisection require on the starting interval [a, b]?
- f(a) = f(b)
- f(a) and f(b) have opposite signs
- f must be differentiable
- a and b must be integers
What is the main advantage of Newton's method over bisection?
- It never fails
- It converges quadratically near a simple root
- It doesn't need a starting point
- It finds all roots at once
Why use a relative stopping test such as abs(dx) < 1e-14 * abs(x)?
- It is faster to compute
- It adapts to the magnitude of the root, unlike a fixed absolute tolerance
- It avoids the derivative
- It guarantees convergence