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.

asked Feb 3, 2013 at 6:54
2
  • 1
    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? Commented Mar 5, 2013 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. Commented Apr 4, 2013 at 9:27

1 Answer 1

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,0431 gold badge26 silver badges29 bronze badges
answered Feb 3, 2013 at 8:04
1
  • (lambda x:x**9, 0.0, 10.0, 100000) for what purpose do we write the numbers after lambda and how is it related to the real function Commented Jan 16, 2017 at 19:50

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.