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)));

### Like this:

Like Loading...

*Related*