[Edu-sig] RE: Integration correction

Kirby Urner urnerk at qwest.net
Tue Mar 29 21:11:06 CEST 2005


> Kirby got the trapezoidal integration rule wrong.
> This is the corrected version.
> 
> def integrate(f,a,b,n=1000):
>     sum = 0
>     h = (b-a)/float(n)
>     for i in range(1,n):
>            sum += f(a+i*h)
>     return h*(0.5*f(a)+sum+0.5*f(b))
> 


Here's the same thing using a generator expression (which is good for
situations like this):

def integrate2(f,a,b,n=1000):
    thesum = 0
    h = (b-a)/float(n)
    thesum = sum(f(a+i*h) for i in range(1,n))
    return (h/2)*(f(a) + f(b)) + thesum*h

Kirby

See: "Composite Trapezoidal Rule"
http://math.fullerton.edu/mathews/n2003/TrapezoidalRuleMod.html





More information about the Edu-sig mailing list