Is there a way to perform the trapezium rule on a set of x and y values in a list? I've got two lists of numbers that when plotted against each other give a bell curve shape, how would I go about finding the area of the curve? I have this code but I cant see how to modify it to work with just two lists of numbers;
def trap0 (f ,a ,b ,n ):
# Basic trapezium rule . Integrate f(x ) over theinterval from a to b using n strips
h= float (b-a)/n
s =0.5*(f(a)+f(b))
for i in range (1,n):
s= s+f(a+i*h)
return s*h
What function, exactly, do you want to integrate? Is it e.g. the one given by sorting the x-coords into order and then interpolating linearly between successive (x,y) pairs?
Or is the idea that you have a bunch of possibly-irregularly-spaced (x,f(x)) pairs, and you want to compute the sum of areas of the trapezoids defined by consecutive pairs (which will be an approximation to the integral of any function going through those points)?
If the former: I suggest something along these lines (danger: untested code):
class PiecewiseLinearFunction:
def __init__(self, xs, ys):
self.coords = zip(xs, ys)
self.coords.sort()
def __call__(self, x):
# I'll let you implement this
# but the idea is to find which interval x lies in, e.g.
# by bisection, and then to evaluate f by linear interpolation
# between the ys on either side
after which you can make an instance of PiecewiseLinearFunction
and pass it to your trap0
function or whatever.
If the latter: sort the (x,y) pairs, perhaps as in the code above, and then compute the area of each trapezoid (width times average height) and add up.