calculator fatigue

tired of tediously punching away at my calculator doing approximate integration I was inspired to whip up a little python script for computing Trapezoid rule, Midpoint rule and Simpson’s rule:

import math
from math import sqrt, log
a,b,n = 0.0,1.0,4.0;
dx = (b-a)/n;

# trapezoid rule
def f(x) :
        return 34*(math.cos(x**2));
x = a;
t = f(x);
x += dx;
while ((x + dx) <= b) :
        tt = f(x);
        t += 2*tt;
        x += dx;
tt = f(x);
t += tt;
ft = (dx/2)*t;
print ("T = " + str(round(ft, 6)));

# midpoint rule
x = a + (dx/2);
m = 0.0;
while (x <= b) :
        mm = f(x);
        m += mm;
        x += dx;

print ("M = " + str(round(dx*m, 6)));

# Simpsons rule
x = a;
s = f(x);
x += dx;
while ((x + 3.0*dx) <= b) :
        ss = f(x);
        s += 4.0*ss;
        x += dx;
        ss = f(x);
        s += 2.0*ss;
        x += dx;

ss = f(x);
s += 4.0*ss;
x += dx;
ss = f(x);
s += ss;
fs = (dx/3)*s;
print ("S = " + str(round(fs,6)));
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s