Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
What is the trouble you are having with the function? Do you have a function which you are having trouble passing into the integrator, in which case you need to say what language you're using, or are you having trouble with the user inputting the function in some form? –  Pete Kirkham Mar 5 '13 at 9:10
The OP might hope to be able to demonstrate the main usefulness of this algorithm for functions that do not have closed form. However, due to the limitation of the chosen input method (interactive console input/output), and the lack of symbolic functions handling (which is outside the scope of OP's original plan), means that the function's evaluations had to be entered point-by-point, which defeats the demonstration of the algorithm's main usefulness. –  rwong Apr 4 '13 at 9:27

1 Answer 1

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.