TExcelTAD
Home › Fortran › Fortran Numerical Integration

Fortran Numerical Integration

Scientific computing was Fortran's original purpose, so the last part of the course applies what you've learned to classic numerical methods. We start with numerical integration (quadrature): approximating ∫ₐᵇ f(x) dx when no formula for the antiderivative exists, or when f is only known at sample points.

All examples use double precision (real64) and pass the integrand as a procedure argument with an abstract interface, as shown in the interfaces lesson.

The trapezoidal rule

Split [a, b] into n equal pieces of width h = (b − a)/n and approximate the area under each piece by a trapezoid:

∫ f dx ≈ h · [ f(x₀)/2 + f(x₁) + … + f(xₙ₋₁) + f(xₙ)/2 ]

fortran · try it yourself
module quadrature
  use iso_fortran_env, only: dp => real64
  implicit none

  abstract interface
    pure function integrand(x) result(y)
      import :: dp
      real(dp), intent(in) :: x
      real(dp) :: y
    end function integrand
  end interface

contains

  function trapezoid(f, a, b, n) result(s)
    procedure(integrand) :: f
    real(dp), intent(in) :: a, b
    integer, intent(in) :: n
    real(dp) :: s, h
    integer :: i
    h = (b - a) / n
    s = 0.5_dp * (f(a) + f(b))
    do i = 1, n - 1
      s = s + f(a + i * h)
    end do
    s = s * h
  end function trapezoid

  pure function gauss_bell(x) result(y)
    real(dp), intent(in) :: x
    real(dp) :: y
    y = exp(-x**2)
  end function gauss_bell

end module quadrature

program trap_demo
  use quadrature
  implicit none
  real(dp), parameter :: exact = 0.746824132812427_dp    ! integral of exp(-x^2) on [0, 1]
  real(dp) :: approx
  integer :: n

  n = 4
  do while (n <= 1024)
    approx = trapezoid(gauss_bell, 0.0_dp, 1.0_dp, n)
    print '(a, i5, a, f16.12, a, es9.2)', 'n =', n, '  I =', approx, '  error =', abs(approx - exact)
    n = n * 4
  end do
end program trap_demo
n =    4  I =  0.742984097800  error = 3.84E-03
n =   16  I =  0.746584596788  error = 2.40E-04
n =   64  I =  0.746809163638  error = 1.50E-05
n =  256  I =  0.746823197246  error = 9.36E-07
n = 1024  I =  0.746824074340  error = 5.85E-08

use iso_fortran_env, only: dp => real64 imports the kind under the short name dp directly.

Each time n is multiplied by 4, the error shrinks by a factor of about 16 = 4²: the trapezoidal rule is second-order accurate, error ∝ h².

Simpson's rule

Fitting parabolas through pairs of intervals instead of straight lines gives Simpson's rule (n must be even):

∫ f dx ≈ h/3 · [ f(x₀) + 4f(x₁) + 2f(x₂) + 4f(x₃) + … + 4f(xₙ₋₁) + f(xₙ) ]

With array syntax the weights become a one-liner:

fortran · try it yourself
module simpson_mod
  use iso_fortran_env, only: dp => real64
  implicit none
contains

  function simpson(y, h) result(s)
    real(dp), intent(in) :: y(0:)       ! samples f(x0) ... f(xn), n even
    real(dp), intent(in) :: h
    real(dp) :: s
    integer :: n
    n = ubound(y, 1)
    s = h / 3.0_dp * (y(0) + y(n) + 4.0_dp * sum(y(1:n-1:2)) + 2.0_dp * sum(y(2:n-2:2)))
  end function simpson

end module simpson_mod

program simpson_demo
  use simpson_mod
  implicit none
  real(dp), parameter :: pi = 4.0_dp * atan(1.0_dp)
  real(dp), allocatable :: x(:), y(:)
  real(dp) :: h, approx
  integer :: n, i

  n = 4
  do while (n <= 64)
    h = pi / n
    x = [(i * h, i = 0, n)]
    y = sin(x)                               ! integral of sin on [0, pi] is exactly 2
    approx = simpson(y, h)
    print '(a, i3, a, f16.12, a, es9.2)', 'n =', n, '  I =', approx, '  error =', abs(approx - 2.0_dp)
    n = n * 2
  end do
end program simpson_demo
n =  4  I =  2.004559754984  error = 4.56E-03
n =  8  I =  2.000269169948  error = 2.69E-04
n = 16  I =  2.000016591048  error = 1.66E-05
n = 32  I =  2.000001033369  error = 1.03E-06
n = 64  I =  2.000000064530  error = 6.45E-08

Halving h cuts the error by about 16 = 2⁴: Simpson's rule is fourth-order. This version works on an array of samples, so it can also integrate measured data.

The dummy argument y(0:) makes the array start at index 0 inside the function, matching the mathematical notation x₀ … xₙ. The strided sections y(1:n-1:2) (odd indices) and y(2:n-2:2) (even interior indices) apply the 4-2-4-2 weights.

Adaptive integration

A fixed step wastes effort where f is smooth and is too coarse where it changes quickly. Adaptive Simpson integration splits an interval only where the estimate isn't accurate enough, a natural use of recursion:

fortran · try it yourself
module adaptive
  use iso_fortran_env, only: dp => real64
  implicit none
  integer :: evaluations = 0
contains

  function f(x) result(y)
    real(dp), intent(in) :: x
    real(dp) :: y
    evaluations = evaluations + 1
    y = sqrt(x)                     ! steep near 0: hard for fixed steps
  end function f

  recursive function asimp(a, b, fa, fm, fb, whole, tol, depth) result(s)
    real(dp), intent(in) :: a, b, fa, fm, fb, whole, tol
    integer, intent(in) :: depth
    real(dp) :: s, m, lm, rm, flm, frm, left, right
    m = 0.5_dp * (a + b)
    lm = 0.5_dp * (a + m)
    rm = 0.5_dp * (m + b)
    flm = f(lm)
    frm = f(rm)
    left = (m - a) / 6.0_dp * (fa + 4.0_dp * flm + fm)
    right = (b - m) / 6.0_dp * (fm + 4.0_dp * frm + fb)
    if (depth <= 0 .or. abs(left + right - whole) <= 15.0_dp * tol) then
      s = left + right + (left + right - whole) / 15.0_dp
    else
      s = asimp(a, m, fa, flm, fm, left, tol / 2, depth - 1) + &
          asimp(m, b, fm, frm, fb, right, tol / 2, depth - 1)
    end if
  end function asimp

  function integrate(a, b, tol) result(s)
    real(dp), intent(in) :: a, b, tol
    real(dp) :: s, fa, fm, fb
    fa = f(a)
    fm = f(0.5_dp * (a + b))
    fb = f(b)
    s = asimp(a, b, fa, fm, fb, (b - a) / 6.0_dp * (fa + 4.0_dp * fm + fb), tol, 50)
  end function integrate

end module adaptive

program adaptive_demo
  use adaptive
  implicit none
  real(dp) :: approx
  real(dp) :: tol
  integer :: k

  tol = 1.0e-4_dp
  do k = 1, 3
    evaluations = 0
    approx = integrate(0.0_dp, 1.0_dp, tol)
    print '(a, es8.1, a, f14.10, a, es9.2, a, i0)', 'tol ', tol, ': I =', approx, &
          '  error =', abs(approx - 2.0_dp / 3.0_dp), '  f calls = ', evaluations
    tol = tol / 100
  end do
end program adaptive_demo
tol  1.0E-04: I =  0.6666639721  error = 2.69E-06  f calls = 37
tol  1.0E-06: I =  0.6666666471  error = 1.95E-08  f calls = 105
tol  1.0E-08: I =  0.6666666666  error = 2.55E-11  f calls = 317

The exact value is 2/3. The algorithm concentrates its points near x = 0, where √x is steep, and the error stays below each requested tolerance.

Tip: For production work, the classic Fortran library QUADPACK (now maintained in modern Fortran as part of several open-source projects) provides robust adaptive Gauss–Kronrod integrators, including ones for infinite intervals and singular integrands.

Test yourself

If you double n in the trapezoidal rule, roughly how does the error change?

  1. Halves
  2. Becomes 4 times smaller
  3. Becomes 16 times smaller
  4. Stays the same

What does the dummy declaration real(dp), intent(in) :: y(0:) do?

  1. Declares an empty array
  2. Makes the assumed-shape array start at index 0 inside the procedure
  3. Requires the caller's array to start at 0
  4. Declares a scalar

Why does adaptive integration need fewer function evaluations for √x on [0, 1]?

  1. It uses a lower precision
  2. It refines only where the local error estimate is too large
  3. It skips the endpoints
  4. It integrates analytically