6.2 The Composite Trapezoidal Rule
137
The Programmer’s Dilemma
1. Specific implementation: Should we write a special program for the
particular integral, using the ideas from the general rule (6.17), but
replacing f by v, x by t, and h by Δt?
2. General implementation: Should we implement the general
method (6.17), as written, in a general function trapezoidal(f,
a, b, n) and solve the particular integral by a specialized call to this
function?
A general implementation is always the best choice, not only for integrals,
but when programming in general!
The first alternative in the box above sounds less abstract and therefore more
attractive to many. Nevertheless, as we hope will be evident from the following,
the second alternative is actually the simplest and most reliable from both a
mathematical and a programming point of view.
These authors will claim that the second alternative is the essence of the power
of mathematics, while the first alternative is the source of much confusion about
mathematics!
General Implementation For the integral
b
a f (x)dx, computed by the formula (6.17), we want a corresponding Python function trapezoidal to take any
f , a, b, and n as input and return the approximation to the integral.
We write trapezoidal as close as possible to the formula (6.17), making sure
variable names correspond to the mathematical notation:
def trapezoidal(f, a, b, n):
h = (b-a)/n
f_sum = 0
for i in range(1, n, 1):
x = a + i*h
f_sum = f_sum + f(x)
return h*(0.5*f(a) + f_sum + 0.5*f(b))
Observe how the for loop takes care of (only) the sum over f (x i ), and that the
x values start with x = a + h (when i is 1), increases with h for each iteration,
before ending with x = a + (n − 1)h. This is consistent with the x values of the
sum in (6.17). After the loop, we finalize the computation and return the result.
This will be our implementation of choice for the trapezoidal function, even
though, typically for programming, it could have been implemented in different
ways. Which implementation to choose, is sometimes just a matter of personal
taste.
One alternative version could be:
def trapezoidal(f, a, b, n):
h = (b-a)/n
result = 0.5*f(a) + 0.5*f(b)
for i in range(1, n):
result += f(a + i*h)
result *= h
return result
Précédent

- 158/350

Suivant