140
6 Computing Integrals and Testing Code
Implementation Without Function Definitions Basically, we use a for loop to
compute the sum. Each term with f (x) in the formula (6.17) is replaced by 3t 2 e t 3 ,
x by t, and h by Δt. 1 A first version of this special implementation, without any
function definition, could read
from math import exp
a = 0.0; b = 1.0
n = int(input(’n: ’))
dt = (b - a)/n
# Integral by the trapezoidal method
v_sum = 0
for i in range(1, n, 1):
t = a + i*dt
v_sum = v_sum + 3*(t**2)*exp(t**3)
numerical = dt*(0.5*3*(a**2)*exp(a**3) +
v_sum +
0.5*3*(b**2)*exp(b**3))
exact_value = exp(1**3) - exp(0**3)
error = abs(exact_value - numerical)
rel_error = (error/exact_value)*100
print(’n={:d}: {:.16f}, error: {:g}’.format(n, numerical, error))
The problem with the above strategy is at least three-fold:
1. To write the code, we had to reformulate (6.17) for our special problem with a
different notation. Errors come easy then.
2. To write the code, we had to insert the integrand 3t 2 e t 3 several places in the code,
which quickly leads to errors.
3. If we later want to compute a different integral, the code must be edited in several
places. Such edits are likely to introduce errors.
The potential errors related to point 2 serve to illustrate how important it is to define
and use appropriate functions.
Implementation with Function Definitions An improved second version of the
special implementation, now with functions for the integrand v and the antiderivative V, might then read
from math import exp
v = lambda t: 3*(t**2)*exp(t**3)
# Define integrand
a = 0.0; b = 1.0
n = int(input(’n: ’))
dt = (b - a)/n
# Integral by the trapezoidal method
1 Replacing h by Δt is not strictly required as many use h as interval also along the time axis.
Nevertheless, Δt is an even more popular notation for a small time interval, so we use that here.
Précédent

- 161/350

Suivant