Using Trapezoids
We can get better approximations sooner using trapezoids rather than rectangles. That way, we won't miss as much area, as you can see in Figure 10.13:
The following is the formula for the trapezoidal rule:
The heights of the segments at the endpoints x = a and x = b are counted once, while all the other heights are counted twice. That's because there are two heights in the formula for the area of a trapezoid. Can you guess how to adapt your integral function to be trapezoidal?
def trap_integral(f,a,b,num): """Returns the sum of num trapezoids under f between a and b""" width = (b-a)/num area = 0.5*width*(f(a) + f(b) + 2*sum([f(a+width*n) for n in range(1,num)])) return area
Now we'll run the
trap_integral...