4

I am trying to implement the trapezoidal rule programmatically but am having trouble finding a good way to input the function of x and then have a loop which will iterate through for each sub-interval finding the area of the trapezium and adding the results and returning it.

Any help would be awesome.

1 Answers1

2

The python example from wikipedia does pretty well:

#!/usr/bin/env python
from __future__ import division

def trapezoidal_rule(f, a, b, n):
    """Approximates the definite integral of f from a to b by
    the composite trapezoidal rule, using n subintervals"""
    h = (b - a) / n
    s = f(a) + f(b)
    for i in xrange(1, n):
        s += 2 * f(a + i * h)
    return s * h / 2


print trapezoidal_rule(lambda x:x**9, 0.0, 10.0, 100000)
# displays 1000000000.75

This example uses two very useful features in python: anonymous/passed functions and iteration over ranges. Similar solutions exist in other languages. A foreach loop would be typical in most. You'd need to produce something equivalent to a first-class function in order to easily generate the "f" parameter.

Peter Taylor
  • 4,043