> 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



_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig

Reply via email to