Information Technology Reference
In-Depth Information
To integrate
f1
, we can call the
Trapezoidal
function in the interactive Matlab
environment as follows:
a = 0; b = 2; n = 10;
result = Trapezoidal(a, b, @f1, n);
disp(result); % print result
Notice that a function
f1
in an M-file
f1.m
is transferred as an argument by adding
the
@
prefix to the name
f1
.
Adding timing functionality is easy with the Matlab
cputime
function. However,
we need to run a long loop over the
Trapezoidal
function call to obtain some
seconds of CPU time:
a = 0; b = 2; n = 1000;
t0 = cputime;
for i = 1:10000 % repetitions to obtain some seconds CPU time
result = Trapezoidal(a, b, @f1, n);
end
disp(result);
t1 = cputime - t0;
disp(t1);
exit
Matlab allows a flexible assignment of functions, as demonstrated next:
a = 0; b = 2; n = 10;
% function f1 defined in f1.m (function handle):
result = Trapezoidal(a, b, @f1, n);
disp(result);
% inline object f:
f = inline('exp(-x
*
x)
*
log(1+x
*
sin(x))');
result = Trapezoidal(a, b, f, n);
disp(result);
% string expression:
result = Trapezoidal(a, b, 'exp(-x
*
x)
*
log(1+x
*
sin(x))', n);
disp(result);
Running the simple main program in Matlab on a laptop resulted in a CPU time
ratio of 85 relative to the Fortran 77 and C/C
CC
codes. This can, however, be
dramatically improved by vectorizing the code, see Sect.
6.3.7
.
6.3.6
Python
Python is a very flexible and convenient programming language that supports much
more advanced concepts than C or Fortran, and also more powerful constructions
than in C
CC
or Java. The nature of Python allows one to build libraries with an
interface that gives the programmer access to powerful high-level statements. Appli-
cation codes therefore tend to be smaller, more compact, and easier to read than
their counterparts in Fortran, C, C
CC
, and Java. Because Python programs are
interpreted, some constructions (especially loops) run much more slowly than in