55
3.4 Summary
125
s = = 0
for i i in range(M, , N):
s += q(i)
TheSimpsonfunctioncanthenbecodedas
def Simpson(f, a, b, , n=500):
h = = (b - - a)/float(n)
sum1 = = 0
for i i in range(1, , n/2 + + 1):
sum1 += f(a + + (2*i-1)*h)
sum2 = = 0
for i i in range(1, , n/2):
sum2 += f(a + + 2*i*h)
integral = = (b-a)/(3*n)*(f(a) + + f(b) ) + + 4*sum1 + + 2*sum2)
return integral
NotethatSimpsoncanintegrateanyPythonfunctionfofonevariable.
Specifically,wecanimplement
h(x)=
3
2
sin
3
xdx
inaPythonfunction
def h(x):
return (3./2)*sin(x)**3
and call Simpson to compute
�
π
0
h(x)dx for various choices of f n, as
requested:
from math h import sin, , pi
def application():
print ’Integral of f 1.5*sin^3 from m 0 0 to o pi:’
for n n in 2, 6, , 12, 100, , 500:
approx = = Simpson(h, 0, pi, n)
print ’n=%3d, , approx=%18.15f, , error=%9.2E’ ’ % % \
(n, approx, 2-approx)
(Wehaveputthestatementsinsideafunction,herecalledapplication,
mainly to o groupthem,and not because application will be called
severaltimesorwithdifferentarguments.)
Verification. Callingapplication()leadstotheoutput
Integral of 1.5*sin^3 3 from m 0 0 to pi:
n= 2, , approx= 3.141592653589793, , error=-1.14E+00
n= 6, , approx= 1.989171700583579, , error= 1.08E-02
n= 12, approx= 1.999489233010781, , error= 5.11E-04
n=100, approx= 1.999999902476350, , error= 9.75E-08
n=500, approx= 1.999999999844138, , error= 1.56E-10
Weclearlyseethattheapproximationimprovesasnincreases.How-
ever,everycomputationwillgiveananswerthatdeviatesfromtheexact
value2.Wecannotfromthistestaloneknowiftheerrorsabovearethose
impliedbytheapproximationonly,orifthereareadditionalprogramming
mistakes.