Sunday, October 6, 2013

So I was doing calculus homework tonight.  Numerical estimation of integrals, using left endpoint, right endpoint, midpoint and trapezoidal estimation.  I thought that it was really tedious to write all that out by hand, so I thought I'd have the computer do it for me.  Voila.  A python script that will numerically estimate integrals.  Although you could just go to Wolfram Alpha.

Edit: added simpson's rule

69 lines of beauty:

#Numerical estimation of integrals
from math import *

def main():

    f = lambda x: x**3
   
    print left(f)
    print right(f)
    print midpoint(f)
    print trapezoid(f)
    f = lambda x: abs(8-x)
    print midpoint(f, 4, 7.0, 13.0)
    print trapezoid(f, 4, 7.0, 13.0)
    print simpson(f, 4, 7.0, 13.0)
    f = lambda x: e**(-5*x**2)
    print trapezoid(f, 4, 0.0, 1.0)
    print midpoint(f, 4, 0.0, 1.0)

    print simpson(f, 4, 0.0, 1.0)

def left(function, n = 20, start = 0.0, end = 10.0):

    s = 0
    dist = end-start
    deltaX = dist/n
    for x in range(n):
        s += function(start + deltaX*x)
    return s*deltaX

def right(function, n = 20, start = 0.0, end = 10.0):

    s = 0
    dist = end-start
    deltaX = dist/n
    for x in range(n):
        s += function(start + deltaX*(x+1))
    return s*deltaX

def midpoint(function, n = 20, start = 0.0, end = 10.0):

    s = 0
    dist = end-start
    deltaX = dist/n
    for x in range(n):
        s += function(start + 1/2.0*(deltaX*x+deltaX*(x+1)))
    return s*deltaX

def trapezoid(function, n = 20, start = 0.0, end = 10.0):

    s = 0
    dist = end-start
    deltaX = dist/n
    for x in range(n+1):
        if x in (0, n):
            s += function(start + deltaX*(x))
        else:
            s += 2*function(start + deltaX*(x))
    return s*deltaX/2

def simpson(function, n = 20, start = 0.0, end = 10.0):
    s = 0
    dist = end-start
    deltaX = dist/n
    for x in range(n+1):
        if x in (0, n):
            s += function(start + deltaX*x)
        elif x%2 == 1:
            s += 4*function(start + deltaX*x)
        else:
            s += 2*function(start + deltaX*x)

    return s*deltaX/3

if __name__ == "__main__":

    main()