Information Technology Reference
In-Depth Information
Here we have used Python's way of formatting strings with printf -syntax (see
page 250 for a brief introduction to printf -style formatting). The Python syntax is
a string, containing slots for variables, followed by % and a list of the variables to be
inserted in the slots.
The dump function for writing u to a file is now straightforward:
def dump (file, u, t0, dt):
"""write array, containing the solution of an ODE, to file"""
time = t0
for i in range(len(u)):
file.write("%g %g\n" % (time, u[i]))
time += dt
The main program, fetching input data from the command line, can be in this form:
if len(sys.argv) <= 2:
print "Usage: %s tstop dt" % sys.argv[0]
sys.exit(1)
tstop = float(sys.argv[1]) # 1st command-line arg
dt = float(sys.argv[2])
# 2nd command-line arg
if dt < 0: dt = 0.004
n = int(tstop/dt)
def f1(u): return -u # right-hand side: du/dt = f(u) = -u
u0 = 1.0
u = heun(f1, u0, dt, n)
print "end value=%g error=%g\n" % (u[-1], u[-1]-exp(-dt * n))
f = open("sol.dat", "w")
dump(f, u, 0.0, dt)
f.close()
import time; print "CPU-time=", time.clock()
The indexing u[-1] means the last element in u , i.e., the same as u[len(u)-1]
( u[-2] is the second last element, and so on).
The solution can, of course, be visualized by invoking a plotting program such
as Gnuplot or Matlab with the sol.dat file. On the other hand, there is a package
called SciTools (developed at the authors' institution) that offers a Matlab-like set
of commands for plotting in Python. Executing
from scitools.std import *
imports all of the array and plotting functionality. The relevant Python statements
for visualizing the computed u as a curve of .t; u .t // points then read
# visualize solution:
t = linspace(0, tstop, u.size)
plot(t, u, axis=[t[0], t[-1], 0.1, 1.1], title='u(t)',
hardcopy='tmp.ps')
6.4.8
Summary
Section 6.3.9 provides a comparison of Fortran 77, C/C CC , Java, Matlab, Python,
and Maple for implementing simple functions and loops. The present section adds
comments regarding the handling of arrays and graphics. The other new program
Search WWH ::




Custom Search