Information Technology Reference
In-Depth Information
class programming, overloaded operators in classes, type checking, and eval / exec .
A suitable background can be gained by looking up these keywords in the index of
H. P. Langtangen's Scripting Tools for Scientific Computations .
We suppose that we have created a class Integration prm (details follow later).
The base class for all integration methods can then be implemented as the Python
class Integration .
class Integration:
"""
Base class for numerical methods for integrating
f(x) over [a,b].
"""
def __init__(self, p):
self.prm = p # Integration_prm object
def integrate(self):
"""Perform integration."""
# to be implemented in subclasses
return "Integration.integrate; not impl. in subclass"
The trapezoidal rule is conveniently realized as a subclass:
class Trapezoidal(Integration):
def __init__(self, p):
Integration.__init__(self, p)
def integrate(self):
p = self.prm; a = p.a; b = p.b; n = p.npoints; f = p.f
h = (b-a)/float(n)
s=0
x=a
for i in range(1,n,1):
x=x+h
s = s + f(x)
s = 0.5 * (f(a) + f(b)) + s
return h * s
Other subclasses implement other integration rules.
The Integration prm class just holds a , b , n ,and f , but it is convenient to
supply the class with functionality for setting default values and for reading infor-
mation from the command line. To set the function f , we use a utility Function ,to
be explained later. For now it is sufficient to know that
Function('sin(x)+1', independent_variable='x'
defines a function of x equal to sin(x)+1 . In other words, the Function utility
allows us to specify Python functions directly from text expressions (!).
Convenient reading of command-line parameters is done with a function
cmldict , which returns all command-line options as a dictionary (say) p ,such
that p[option]=value .Thatis, -a 0.1 on the command-line results in p['a']
being 0.1. Alternatively, we can traverse the array of command-line strings as we
did in the Java code. Here is the code for the parameter class:
class Integration_prm:
"""
Holds all parameters needed to initialize objects
 
Search WWH ::




Custom Search