Information Technology Reference
In-Depth Information
i in range(p,q+1,r) ,orjust for i in range(q) if the indices from 0 up to
and including q-1 are wanted (these for loops can only work with integer counters).
Python codes are interpreted. Hence, there is no need to compile the file contain-
ing the code; just write the name of the file, int.py , to execute it under Unix, or
write
python int.py
which works under all operating systems where Python is installed.
Python also allows interactive computing. You can write python on the com-
mand line to enter Python's interactive mode, but we recommend using the more
user-friendly IDLE shell that comes with the Python source code distribution. 9 Start
with
from int import *
where int.py is the complete Python program shown above. The import statement
causes all the statements in int.py to be executed, including the integral compu-
tations at the end of the file. 10 The nice thing is that we have, through the import
statement, defined the functions Trapezoidal and f1 , so we can easily experiment
with, e.g., the n value as follows:
>>> from int import *
0.250467798247 70.6
>>> n=10; Trapezoidal(a, b, f1, n)
0.25021765112667527
>>> n=1000; Trapezoidal(a, b, f1, n)
0.25046779824710441
>>> n=3; Trapezoidal(a, b, f1, n)
0.24752392127618572
The Python program executed on a laptop machine resulted in a CPU time ratio of
14 relative to the Fortran 77 and C/C CC codes. The next section explains how to
significantly improve the CPU time.
6.3.7
Vectorization
We have seen that both Matlab and Python enable implementation of the trape-
zoidal rule close to the syntax used in Algorithm 6.2 , but the code is interpreted and
runs much more slowly than in Fortran, C, C CC , and Java. Loops in interpreted
languages will run slowly; actually, such languages are not meant for intensive
numerical computations in explicit for loops - this is a kind of misuse of the
9 If PYTHONSRC is the root of the Python source code tree, the IDLE shell is launched by executing
PYTHONSRC/Tools/idle/idle.py . You should make an alias for this (long) path in your
working environment.
10 The CPU time of the computations is significant, so you would probably get rid of the repetitive
calls to Trapezoidal before using int.py in interactive mode.
Search WWH ::




Custom Search