Professional Documents
Culture Documents
Numerical Integration 2
Numerical Integration 2
Rectangle Rule
In [12]: def CompLeftRect(f, a, b, m):
# m = number of subintervals
# a = lower bound
# b = upper bound
step = (b-a)/m
s = 0
for k in range(m):
s +=f(a+k*step)
return step*s
In [14]: CompLeftRect(f,0,1,3)
Out[14]: 0.7833333333333333
In [16]: CompRightRect(f,0,1,3)
Out[16]: 0.6166666666666667
Midpoint Rule
In [18]: CompMidPoint(f, 0, 1, 3)
Out[18]: 0.6897546897546897
Trapezoidal Rule
In [20]: def CompTrapezeRule(f, a, b, m):
# m = number of subintervals
# a = lower bound
# b = upper bound
step = (b-a)/m
s = (f(a)+f(b))/2
for k in range(1,m):
s +=f(a+k*step)
return step*s
In [22]: CompTrapezeRule(f, 0, 1, 3)
Out[22]: 0.7
Simpson Rule
In [47]: def SimpsonRule(f,a,b):
return (b-a)/6*(f(a)+4*f(0.5*(a+b))+f(b))
def CompSimpsonRule(f,a,b,m):
s = 0
step = (b-a)/m
for k in range(m):
s += SimpsonRule(f,a+k*step,a+(k+1)*step)
return s
In [46]: CompSimpsonRule(f,0,1,3)
Out[46]: 0.6931697931697931
In [38]: SimpsonRule(f,0,1)
Out[38]: 0.6944444444444443
Out[50]: [2.656889614809846,
11.69363458636176,
4.317319736680682,
7.175262100585803,
5.2699671913157236]
In [ ]: