Information Technology Reference
In-Depth Information
result = i.integrate()
print result
Running such a type of Python program with
-a 0 -b 2 -m Trapezoidal -f '1+x * x * x'
as command-line arguments gives the result 6.04.
The details of the Function class are not important, but the code is listed here for
reference and to demonstrate how easy it is with Python to build a convenient utility
for representing functions. This utility can be used to hold either Python functions
or string definitions of functions. 21
class Function:
"""
Unified treatment of functions; strings or function objects.
Examples on usage:
def myfunc(x):
return 1+x
f = Function(myfunc, 'x') # attach Python function
v = f(1.2)
f = Function('1+t', 't')
# specify function by string
v = f(1.2)
"""
def __init__(self, f, independent_variable='x'):
self.f = f # expression or function object
self.var = independent_variable # 'x', 't' etc.
if type(f) == type(""):
self.f_is_string = 1
self.__name__ = self.f
else:
# function object:
self.f_is_string = 0
self.__name__ = self.f.__name__
def __call__(self, x):
if self.f_is_string:
exec("%s = %g" % (self.var, x))
return eval(self.f)
else:
return self.f(x)
6.5.6
Object-Oriented Programming in Matlab
The Matlab language supports object-oriented programming. Nevertheless, these
authors find it is more convenient to perform object-oriented programming in lan-
guages such as Java, C CC , and Python. These languages were originally designed
21 Class Function implements the flexibility of the fcnchk function in Matlab, but results in
nicer call syntax (functions represented as Function instances are called like any other Python
functions).
Search WWH ::




Custom Search