Information Technology Reference
In-Depth Information
and performing the integration with the desired method and function with just one
line of code (!):
exec("r = %s(a, b, lambda x: %s, n)" % (method, function_expression))
The integration result is stored in the variable r .The lambda construction is a way
of defining a type of inline function. More straight and less compact code could be
a multi-line string such as
exec("""
def myf(x):
return %s
r = %s(a, b, myf, n)
""")
Of course, this construction of code at run time works only if all integration
functions have the same set of parameters, here a , b , f ,and n . This may not be
the case when we extend the libraries with more sophisticated integration methods.
For example, we can think of methods producing a result with an error less than
a specified tolerance. Such methods can take the tolerance and additional parame-
ters, specifying numerical details (such as the order of the integration scheme) as
input arguments. A flexible library for numerical integration could have a method
collection such as the following:
- Trapezoidal ( a , b , f , n )
- Simpson ( a , b , f , n )
- AdaptiveTrapezoidal ( a , b , f , n max , )
- AdaptiveSimpson ( a , b , f , n max , )
- AdaptiveGaussLegendre ( a , b , f , n max , , p 1 , p 2 )
- GeneralGaussLobatto ( a , b , f , n , q 1 , q 2 , q 3 )
Here we have just listed some functions for illustrating that the number and type of
arguments differ among the functions.
In the if-else approach it is easy to cope with differing argument lists in the
function calls, since each call is written explicitly the way it is required. However,
in large codes if-else tests tend to be long, and the same tests are often repeated
in many places in the code. This assertion may be less easy to realize from the
present simple integration example, but the authors' experience with building large
numerical codes points to repeated if-else lists as a major problem. When a new
integration method is added to the library, the programmer must remember to add
a call to the new function in all relevant if-else tests throughout the code. If the
numerical software counts some hundred thousand lines of code, this is a tedious and
error-prone task. We shall therefore present a better way of implementing flexible
choices of numerical algorithms.
Every time we need to integrate a function in the code, we would like to issue a
statement where we do not need to see what type of method that is being used or
what type of parameter is needed. The advantage of such an approach is obvious: All
calls to numerical integration routines will work with a new method when we have
Search WWH ::




Custom Search