Algorithm for the trapezoidal rule

The trapezoidal rule is easy to implement numerically through the following simple algorithm

  • Choose the number of mesh points and fix the step length.
  • calculate \( f(a) \) and \( f(b) \) and multiply with \( h/2 \).
  • Perform a loop over \( n=1 \) to \( n-1 \) (\( f(a) \) and \( f(b) \) are known) and sum up the terms \( f(a+h) +f(a+2h)+f(a+3h)+\dots +f(b-h) \). Each step in the loop corresponds to a given value \( a+nh \).
  • Multiply the final result by \( h \) and add \( hf(a)/2 \) and \( hf(b)/2 \).