138
6 Computing Integrals and Testing Code
where 0.5*f(a) + 0.5*f(b) is used in an initialization of result, before adding
all the function evaluations f (x i ) in the loop. After the loop, the only remaining
thing, is to multiply by h. In this second alternative, there are also a few other
differences to note. The range function is called with two parameters only, giving
the (default) step of 1. In the loop, instead of computing x = a + i*h prior to
calling f(x), we combine this into f(a + i*h), which first computes a + i*h
and then makes the call to f. Also, the compact operators += and *= have been
used.
Using the General Implementation in a Session Having the trapezoidal
function as the only content of a file trapezoidal.py automatically makes that
file a module that we can import and test in an interactive session:
In [1]: from trapezoidal import trapezoidal
In [2]: from math import exp
In [3]: v = lambda t: 3*(t**2)*exp(t**3)
In [4]: n = 4
In [5]: numerical = trapezoidal(v, 0, 1, n)
In [6]: numerical
Out[6]: 1.9227167504675762
Let us compute the exact expression and the error in the approximation. Using V
for the anti-derivative, we get:
In [7]: V = lambda t: exp(t**3)
In [8]: exact = V(1) - V(0)
In [9]: abs(exact - numerical)
# absolute value of error
Out[9]: 0.20443492200853108
Since the sign of the error is irrelevant, we find the absolute value of the error. So,
is this error convincing? We can try a larger n:
In [10]: numerical = trapezoidal(v, 0, 1, n=400)
In [11]: abs(exact - numerical)
Out[11]: 2.1236490512777095e-05
Fortunately, many more trapezoids give a much smaller error.
Using the General Implementation in a Program Instead of computing our
integral in an interactive session, we can do it in a program. In that program, we
need the (general) function definition of trapezoidal, and we need some code
that specifies our particular integrand, as well as the other arguments required for
calling trapezoidal. This code might be placed in a main program. However, it
could also be placed in a function that is called from the main program. This is what
we will do. A chunk of code doing a particular thing is always best isolated as a
function, even if we do not see any future reason to call the function several times,
and even if we have no need for arguments to parameterize what goes on inside the
Précédent

- 159/350

Suivant