Information Technology Reference
In-Depth Information
Fortran, C, C CC , or Java. However, for many applications Python is fast enough,
in scientific computing contexts as well [19]. Only a glimpse of Python is given
below. The reader is referred to the topic [20] for a more comprehensive treatment
of Python's applicability in a numerical context.
Matlab and Python have much in common: Both are easy to learn, they have a
very clean syntax, and they have high-level tools for performing compound oper-
ations in a few statements. Matlab has more built-in functionality for scientific
computing, but Python is a more advanced and flexible programming environment.
A good strategy is to use Matlab for tasks where Matlab is strong, mainly linear
algebra-related problems, and build your own, tailored Matlab-like environment
via Python for more advanced tasks. Of course, Python can also be used for linear
algebra problems.
Variables in Python can readily be brought into play, without explicitly men-
tioning their type. Since the Python syntax (like Matlab's) is close to mathematical
notation, the difference between Algorithm 6.2 and Python code is small:
#!/usr/bin/env python
from math import *
def Trapezoidal(a, b, f, n):
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
def f1(x):
f = exp(-x * x) * log(1+x * sin(x))
return f
def f2(x):
# simple function for verification
return 1 + x
# integral from 0 to 2 should be 4
a = 0; b = 2; n = 1000
for i in range(10000):
result = Trapezoidal(a, b, f1, n)
import time # measure time spent in the program
t1 = time.clock() # CPU time so far in the program
print result, t1
This is the complete code; the trapezoidal function, the test function f1 to be
integrated, and a main program calling up the integration 1,000 times such that mea-
surements of the CPU time become reliable. As in most other languages, we need to
import library functionality, here through the import statement. Most of the syntax
should be self-explanatory, even for the novice 8 with the exception, perhaps, that
functions are prefixed by def and for loops from p to q in steps of r are written for
8 The intuitive treatment of functions as arguments in functions, cf. the f variable in function
Trapezoidal , is considerably simpler and clearer than the corresponding treatment of function
arguments in the other languages we treat herein.
Search WWH ::




Custom Search