Professional Documents
Culture Documents
1 On models 1
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Classification of chemical process models . . . . . . . . . 4
1.3 Lumped parameter, steady state models . . . . . . . . . . 5
1.3.1 Example of a stagewise separation process . . . . 5
1.3.2 Process flow sheet simulation . . . . . . . . . . . . 9
1.3.3 Example of a multicomponent flash . . . . . . . . . 11
1.3.4 Example of a phenomenalogical model . . . . . . . 13
1.3.5 Example of reactors in series . . . . . . . . . . . . . 14
1.4 Lumped parameter, dynamic models . . . . . . . . . . . . 15
1.4.1 Example of cooling a molten metal . . . . . . . . . 15
1.4.2 Ozone decomposition . . . . . . . . . . . . . . . . . 16
1.5 Distributed parameter, steady state models . . . . . . . . 17
1.5.1 Heat transfer through a tappered fin . . . . . . . . 17
1.6 Distributed parameter, dynamic models . . . . . . . . . . 20
1.6.1 Heat transfer through a tappered fin . . . . . . . . 20
i
CONTENTS ii
4 Nonlinear equations 89
4.1 Newton’s method . . . . . . . . . . . . . . . . . . . . . . . . 90
4.2 Euler-Newton continuation . . . . . . . . . . . . . . . . . . 96
4.3 Arc-length continuation . . . . . . . . . . . . . . . . . . . . 96
4.4 Quasi-Newton methods . . . . . . . . . . . . . . . . . . . . 96
4.4.1 Levenberg-Marquadt method . . . . . . . . . . . . . 96
4.4.2 Steepest descent method . . . . . . . . . . . . . . . 96
4.4.3 Broyden’s method . . . . . . . . . . . . . . . . . . . 96
4.5 Exercise problems . . . . . . . . . . . . . . . . . . . . . . . 96
4.5.1 Turbulent flow through a pipeline network . . . . 96
5 Functional approximations 98
5.1 Approximate representation of functions . . . . . . . . . 99
5.1.1 Series expansion . . . . . . . . . . . . . . . . . . . . 99
5.1.2 Polynomial approximation . . . . . . . . . . . . . . 99
5.2 Approximate representation of data . . . . . . . . . . . . . 104
5.2.1 Least squares approximation . . . . . . . . . . . . . 105
5.3 Difference operators . . . . . . . . . . . . . . . . . . . . . . 107
5.3.1 Operator algebra . . . . . . . . . . . . . . . . . . . . 108
5.3.2 Newton forward difference approximation . . . . . 109
5.3.3 Newton backward difference approximation . . . . 112
5.4 Inverse interpolation . . . . . . . . . . . . . . . . . . . . . . 116
5.5 Lagrange polynomials . . . . . . . . . . . . . . . . . . . . . 118
5.6 Numerical differentiation . . . . . . . . . . . . . . . . . . . 122
5.6.1 Approximations for first order derivatives . . . . . 122
5.6.2 Approximations for second order derivatives . . . 124
5.6.3 Taylor series approach . . . . . . . . . . . . . . . . . 126
5.7 Numerical integration . . . . . . . . . . . . . . . . . . . . . 126
5.7.1 Romberg Extrapolation . . . . . . . . . . . . . . . . 129
5.7.2 Gaussian quadratures . . . . . . . . . . . . . . . . . 132
5.7.3 Multiple integrals . . . . . . . . . . . . . . . . . . . . 132
5.8 Orthogonal functions . . . . . . . . . . . . . . . . . . . . . 132
5.9 Piecewise continuous functions - splines . . . . . . . . . . 132
Bibliography R.1
List of Tables
vii
List of Figures
viii
LIST OF FIGURES 1
— WILLIAM BLAKE
Chapter 1
1.1 Introduction
1
1.1. INTRODUCTION 2
Numerical model
Input (an approximation to the mathematical model) Output
examples
ASPEN, HYSIM,
PROCESS, FLOW3D,
HCOMP, SPEEDUP,
DREM
matical model and that between the mathematical model and the numer-
ical approximation. One is well served to remember the cliche garbage
in, garbage out!
In this course we examine the link between the mathematical and
the numerical model. In so doing modern computational tools are used
quite liberally. Concepts of a networked computer environment are dis-
cussed in Appendix A. A basic introduction to MATLAB can be found
in Appendix B. MATLAB is used throughout in illustrating various algo-
rithms.
L, x0 x1 x2 L, x3
1 2 3
V, y1 y2 y3 V, y4
yn = Kxn n = 1, 2, 3 (1.1)
Note that in each of these equations, the left hand side represents the
amount of pollutant that has been removed from the gas phase and the
right hand side represents the same amount of material absorbed into
1.3. LUMPED PARAMETER, STEADY STATE MODELS 7
the liquid phase. Now we have a total of six equations, but still ten
variables. Hence we conclude that we have four degrees of freedom.
This implies that we can choose four of the variables and the remaining
six variables must be determined by satisfying the six equations.
One can also write an overall balance, taking all three stages as one
group:
Overall: V (y4 − y1 ) = L(x3 − x0 ) (1.3)
Let us assume that we pick the four variables associated with the inlet
streams to be specified, viz. (L, V , x0 , y4 ). Defining S = L/KV (a known
value) and eliminating variables (y1 , y2 , y3 ) from equations (1.2) we get
the following system of three equations
(1 + S) −1 0 x1 Sx0
−S (1 + S) −1 x2 = 0 (1.4)
0 −S (1 + S) x3 y4 /K
and
x1 b1 Sx0
x = x2 b = b2 = 0
x3 b3 y4 /K
y = f(x)
x
K
y=
1
x
x)
1
K(
K=constant
y=
1
x x1 x
solved within the conceptual frame work (i) estimating an initial guess
(ii) devising an algorithm to improve the estimate and (iii) checking for
convergence of the result.
or
x + 0.306R = 101.475
1.3. LUMPED PARAMETER, STEADY STATE MODELS 10
mole fr of H2 = 0.694
mole fr of CO= 0.302
R (recycle rate) mole fr of CH3OH= 0.004
Reactor Condenser
x: CO P (rate): CH3OH
y: H2
loop 1
or
y + 0.702R = 225.775
or
x + 0.306R = 101.475
C-balance: x=P
H2 -balance: y = 2P
1.3. LUMPED PARAMETER, STEADY STATE MODELS 11
Recognizing the redundancy between the first and third equations and
also combining equations four and five to eliminate P , we can write the
above set in an alternate form as
1 0 0.306 x 101.475
0 1 0.702 y = 225.775 (1.8)
−2 1 0 R 0
V
yi i=1 .. N
40
Non-physical
30 solution
20
10
F f(ψ)
0
Zi i=1 .. N
TF 10
PF Real solution
20
30
3 2 1 0 1 2 3
L ψ
xi i=1 .. N
F =V +L (1.11)
N
X (1 − Ki )zi
=0 (1.13)
i
(Ki − 1)ψ + 1
a0 a1 ai-1 ai aN-1 aN
F
1 i N
V V V
r = kV a2i
Lumped parameter, dynamic models arise typically when the spatial vari-
ation of the state variables can be ignored for some reason, but time vari-
ation cannot be ignored. Let us consider an example from heat transfer.
Insulation
Molten metal
T1
T2
T∞
where
" # h A h1 A1
T1 − m11Cp1 m1 Cp1 0
θ= A= h A
1
h A +h A
b= h2 A2 T∞
T2 + m21Cp1 − 1 m12 Cp2 2 m2 Cp2
2 2
O3 + O2 z O + 2O2
O3 + O → 2O2
1.5. DISTRIBUTED PARAMETER, STEADY STATE MODELS 17
dy1
= f1 (y1 , y2 ) = −y1 − y1 y2 + κy2 (1.20)
dt
dy2
= f2 (y1 , y2 ) = y1 − y1 y2 − κy2 (1.21)
dt
The initial compositions are y(t = 0) = [1.0, 0.0]. The parameters are
= 1/98 and κ = 3.0. This is a system of two non-linear ordinary dif-
ferential equations. It is an interesting problem in the limit of → 0. In
the reaction analysis literature, the consequence of this limit is known
as the quasi-steady-state-approximation. The physical interpretation is
that the second reaction is much faster than the first one so that it can
be assumed to have reached the equilibirum state at every instant of
time. The second equation becomes an albegraic one. In the applied
mathematics literatture it is called the singular perturbation problem.
From the computational point of view this limit gives rise to a phenom-
ena called stiff systems. We will explore these features further in later
chapters.
W
L
hP δx
T(x) T∞
T0
δx
hP δx
t0
y z
qA|x qA|x+δx
x
of a planar fin shown in figure 1.8a. The base of the fin is maintained
at a uniform temperature of T0 and the ambient temperature is T∞ . The
state variable that we are interested in predicting is the temperature of
the fin, T . In general in might be a function of all three spatial positions
i.e., T (x, y, z). (Note time, t is eliminated by assuming steady state). If
we know something about the length scales of the fin and the material
property of the fin, we make further assumptions that will reduce the
complexity of the problem. Let us also assume that the fin is made of a What types of
homogeneous material i.e., its thermal conductivity, k is independent of materials might
position. If the length, L, of the fin is much larger than the thickness, t0 , violate this
assumption?
then we might argue that the temperature variation in the y direction
will be smaller than that in the x direction. Thus we can assume T to
be uniform in the y direction. Next, we examine what happens in the
z direction? This argument is somewhat subtle as it is based on sym-
metries in the system. The basic premise here is that symmetric causes
produce symmetric effects. An excellent and easily accessible exposi-
tion on this topic can be found in Golubiksky and Stewart (1993). First
we assume that the ends of the fin in the z direction are at infinity (or
W >> L) so that the end effects can be neglected. Since the temperature
gradient within the fin is caused by the driving force T0 and T∞ which
are independent of z direction, we can expect the fin to respond in a
1.5. DISTRIBUTED PARAMETER, STEADY STATE MODELS 19
T (x = 0) = T0
T (x = L) = T∞ (1.23)
dT = 0
dx x=L
1.6. DISTRIBUTED PARAMETER, DYNAMIC MODELS 20
This problem can be solved to obtain T (x) provided the geometrical pa-
rameters {A(x), P }, the material property, k and the heat transfer envi-
ronment {h, T∞ , To } are known. The problem is nonlinear if the thermal
conductivity is a fucntion of temperature, k(T ). In order to determine
the effectiveness of the fin, one is interested in the total rate of heat
transfer, Q through the fin. This is can be computed in one of two ways
as given by,
ZL
dT
Q= hP [T (x) − T∞ ] dx = −k · A(x = 0)
o dx x=0
∂(ρACp T ) ∂ ∂T
= kA − hP (T − T∞ ) (1.24)
∂t ∂x ∂x
IC : T (x, t = 0) = T∞ ,
BC1 : T (x = 0, t) = T0 , (1.25)
BC2 : T (x = L, t) = T∞
Detection is, or ought to be, an exact science, and
should be treated in the same cold and unemotional
manner. You have attempted to tinge it with ro-
manticism, which produces much the same effect
as if you worked a love-story or an elopement into
the fifth proposition of Euclid.
Chapter 2
2.1 Introduction
f (x) = 0 (2.1)
f (x; p) = 0 (2.2)
22
2.1. INTRODUCTION 23
(a) f(x) := sin(x), f(r)=0 at r=nπ, n=0,1,.. (b) f(x):= x3 + 4 x2 + x -6, f(r)=0 at r=-3,-2,1
1
10
0.5 7.5
5
0 2.5
0
-0.5
-2.5
-5
-1
-7.5 -5 -2.5 0 2.5 5 7.5 -3 -2 -1 0 1 2 3
(c) f(x):= x3 + 3 x2 - 4, f(r)=0 at r=-2,-2,1 (d) f(x):= x3 - x2 + x - 1, f(r)=0 at r=1
6
10
4 5
2 0
0 -5
-2 -10
-4 -15
-3 -2 -1 0 1 2 3 -3 -2 -1 0 1 2 3
f (x) := sin(x) = 0
then any complex root must occur in pairs. Consider the three cubic
equations given below:
The crux of the algorithm is often in the second step and the objective
in devising various clever schemes is to get from the initial guess to the
final result as quickly as possible.
(x x )
x3 = x1 − f 1 2 − 1
(f 2 − f 1 )
{ δ
x2 = x1 −
f1
f ’1
x1 + x2
x3 = (2.3)
2
|xi+1 − xi | ≤
|f (xi )| ≤
N
X (1 − Ki )zi
=0 (2.4)
i
(Ki − 1)ψ + 1
function r=bisect(Fun,x,tol,trace)
%BISECT find the root of "Fun" using bisection scheme
% Fun - the name of the external function
% x - vector of length 2, (initial guesses)
% tol - error criterion
% trace - print intermediate results
%
% Usage bisect(’flash’,[0,1])
% flash is the name of the external function.
% [0,1] is the initial guess
%Check inputs
if nargin < 4, trace=0; end
if nargin < 3, tol=eps; trace=0; end
if (length(x) ˜= 2)
error(’Please provide two initial guesses’)
end
function f=flash(psi)
% K is a vector of any length of equil ratios.
% z is the feed composition (same length as K)
% K, z are defined as global in main
% psi is the vapor fraction.
global K z
if ( length(K) ˜= length(z) )
error(’Number of K values & compositions do not match’)
end
n=length(psi);
for i = 1:n
f(i)=sum( ((K-1).*z) ./ (1+(K-1)*psi(i)) );
end
Observe that this function, while being concise, is fairly general to han-
dle any number of components N and a vector of guesses psi of any
length and return a vector of function values, one corresponding to each
element in the guessed variable psi. Assuming that you have such a
function defined in a file named flash.m, you are encouraged to work
through the following exercise using MATLAB.
» global K z
» z=[.25 .25 .25 .25] %define a 4-component system
» K=[2 1.5 0.5 0.1] %define equilibrium values
» bisect(’flash’,[0,.1]) %find the root using bisect ans=0.0434
» x=0:0.05:1; %create a vector of equally spaced data
» y=flash(x); %evaluate the function
» plot(x,y) %plot the function
Instead of using the average of the two initial guesses as we did with
the bisection scheme, we can attempt to approximate the function f (x)
by straight line (a linear approximation) since we know two points on
the function f (x). This is illustrated graphically in figure 2.2b with the
dashed line approximating the function. We can then determine the root,
x3 of this linear function, f˜(x̃). The equation for the dashed straight
line in figure 2.2b is
x̃ − x1 x2 − x 1
f˜(x̃) := =
f˜ − f1 f2 − f 1
x2 − x 1
x3 = x1 − f1 (2.5)
f2 − f 1
function r=secant(Fun,x,tol,trace)
%SECANT find the root of a function "Fun" using secant scheme
% Fun - the name of the external function
% x - vector of length 2, (initial guesses)
% tol - error criterion
% trace - print intermediate results
%
% Usage secant(’flash’,[0,1])
% Here flash is the name of the external function.
% [0,1] is the initial guess
%Check inputs
if nargin < 4, trace=0; end
if nargin < 3, tol=eps; trace=0; end
if (length(x) ˜= 2)
error(’Please provide two initial guesses’)
end
secant method is shown in figure 2.4. The convergence rate of the se-
cant method was analyzed by Jeeves (1958).
The Newton method is by far the most powerful and widely used algo-
rithm for finding the roots of nonlinear equations. A graphical repre-
sentation of the algorithm is shown in figure 2.2d. This algorithm also
relies on constructing a linear approximation of the function; But this is
achieved by taking the tangent to the function at a given point. Hence
this scheme requires only one initial guess, x1 . The linear function f˜(x̃)
shown by dashed line in figure 2.2d is,
f˜ − f1
f˜(x̃) :=
x̃ − x1
f1
x2 = x1 − (2.6)
f10
which forms the iterative process (step 2). Note that this algorithm re-
quires that the derivative of the function be evaluated at every iteration,
which can be a computationally expensive operation.
While we have relied on the geometrical interpretation so far in con-
structing the algorithms, we can also derive Newton’s scheme from a
Taylor series expansion of a function. This is an instructive exercise,
for it will enable us to generalize the Newton’s scheme to higher dimen-
sional ( i.e., more than two equations) systems as well as provide some
information on the rate of convergence of the iterative scheme.
The Taylor series representation of a function around a reference
point, xi is,
X∞
f (k) (xi ) k
f (xi + δ) = δ (2.7)
k=0
k!
where f (k) (xi ) is the k−th derivative of the function at xi and δ is a small
displacement from xi . While the infinite series expansion is an exact
representation of the function, it requires all the higher order derivative
of the function at the reference point. We can construct various levels of
2.6. MULLER’S METHOD 32
where the symbol O(δ3 ) stands as a reminder of the higher order terms
(three and above in this case) that have been neglected. The error in-
troduced by such omission of higher order terms is called truncation
error. In fact to derive the Newton scheme, we neglect the quadratic
term O(δ2 ) also. In figure 2.2d, taking the reference point to be xi = x1 ,
the displacement to be δ = xi+1 − xi , and recognising that f˜(xi + δ) = 0
we can rewrite the truncted two-term series as,
f (xi )
xi+1 = xi −
f 0 (xi )
p2 (v) = av 2 + bv + c
h1 = x1 - x0
f2 h2 = x0 - x2
The reason for coordinate shift should be clear by now. This enables c
to be found directly. Solving the remaining two equations we obtain a
and b as follows:
γf1 − f0 (1 + γ) + f2
a=
γh21 (1 + γ)
f1 − f0 − ah21
b=
h1
where γ = h2 /h1 . So far we have only constructed an approximate rep-
resentation of the original function, f (x) ≈ p2 (v). The next step is to
find the roots of this approximate function, p2 (v) = 0. These are given
by, √
−b ± b2 − 4ac
v = r̃ − x0 =
a2
2.7. FIXED POINT ITERATION 34
2c
r̃ = x0 − √ (2.8)
b± b2 − 4ac
Since p2 (v) is a quadratic, there are clearly two roots r̃ in equation (2.8).
In order the take the root closest to x0 we choose the largest denominator
in equation (2.8). In summary, the sequential procedure for impliment-
ing Muller’s scheme is as follows:
• Guess (x0 , x1 , x2 )
• Compute c = f (x0 ).
Note that Muller’s method converges almost quadratically (as does New-
ton’s scheme), but requires only one additional function evaluation at
every iteration which is comparable to the computational load of the se-
cant method. In particular derivative evaluation is not required, which is
a major advantage as compared to Newton’s method. Also, this scheme
can converge to complex roots even while starting with real initial guesses
as long as provision is made for handling complex arithmetic in the com-
puter program. MATLAB handles complex arithmetic quite naturally.
x = g(x)
2.7. FIXED POINT ITERATION 35
Then, starting with a guess xi , we can evaluate g(xi ) from the right hand
side of the above equation and the result itself is regarded as a better
estimate of the root, i.e.,
f (x) = x 2 − x − 6 = 0 (2.10)
(a) g ( x ) =
x + 6 6
(b) g ( x ) = ( x − 1 )
x
y=
x
y=
|g’(r=3) = -3/2 | > 1 r
x0
y=g(x) r
)
g’(r=3) = 1/6 < 1 =g(x
r x1 y
|g’(r=-2) = -2/3| < 1
x0
(c) g ( x ) = ( x2 − 6 )
y=g(x)
x
y=
g’(r=3) = 6 > 1
r
x0
Iteration Iterate
Number
x1 5.0000000
x2 3.3166248
x3 3.0523147
x4 3.0087065
x5 3.0014507
x6 3.0002418
x7 3.0000403
x8 3.0000067
x9 3.0000011
x10 3.0000002
p
Table 2.1: The first ten iterates of xi+1 = xi + 6 starting with x0 = 5
function x=g(x)
for i=1:10
fprintf(1,’%2i %12.5e\n’,i,x); %print the iterates
x=sqrt(x+6); %also try x=6/(x-1) and x=(xˆ2-6) here
end
Invoke this function from within MATLAB with various initial guesses,
e.g., try initial guess of 5 by entering,
» g(5)
A simple error analysis can be developed for the fixed point iterative
scheme which will provide not only a criterion for convergence, but also
clues for accelerating convergence with very little additional computa-
tional effort. We are clearly moving away from the realm of intuition to
the realm of analysis! Consider the fixed point iteration xi+1 = g(xi ).
After convergence to the root r we will have r = g(r ). Subtracting the
two equations we get,
xi
g(xi) - g(r)
g’(ξ)
xi - r
ξ
r
r < ξ <xi
g(xi ) − g(r )
(xi+1 − r ) = (xi − r )
(xi − r )
where we have used the mean value theorem to replace slope of the
chord by the tangent to the curve at some suitable value of x = ξ, i.e.,
(g(xi ) − g(r ))
= g 0 (ξ)
(xi − r )
It should be clear now that en → 0 as n → ∞ only if |K| < 1. . We refer Well, if we know
to equation (2.12) as the error propagation solution since it provides a the error in the
solution of estimating the error at any step n, provided the error at the first step, none of
this analysis would
first step e1 and K are known.
be necessary!
We can develop a convergence acceleration scheme using the error so-
r = x1 − e1 would
lution (2.12) to estimate the three unknowns (r , K, e1 ) in the second form do it!
of equation (2.12). Once we have generated three iterates, (xn , xn+1 , xn+2 ),
we can use equation (2.12) to write down,
xn = r + K n−1 e1
xn+1 = r + K n e1 (2.13)
n+1
xn+2 = r +K e1
∆xn = xn+1 − xn
You can verify that using equation (2.13) in the above definitions, we get,
(∆xn )2
= K n−1 e1 = xn − r
∆2 x n
2.8. ERROR ANALYSIS AND CONVERGENCE ACCELERATION 40
2 2
(∆xn )2 xn+1 − 2xn xn+1 + xn
r = xn − = xn −
∆ 2 xn xn+2 − 2xn+1 + xn
Thus the three iterates (xn , xn+1 , xn+2 ) can be plugged into the right
hand side of the above equation to get a better estimate of r .
x1 = 5.0000000
x2 = 3.3166248
x3 = 3.0523147
∆x1 = (x2 − x1 ) = −1.6833752
∆x2 = (x3 − x2 ) = −0.26431010
∆2 x1 = (∆x2 − ∆x1 ) = 1.41906510
(∆x1 )2 (−1.6833752)2
r = x1 − = 5.000000 − = 3.0030852
∆ 2 x1 1.41906510
Compare this with the fourth iterate produce in the original sequence
x4 = 3.0087065.
step and ask the question about the rate of convergence of the Newton
method. A Taylor series expansion of g(x) around r is,
g 00 (r )
g(xn ) = g(r ) + g 0 (r )(xn − r ) + (xn − r )2 + · · ·
2
Recognizing that en+1 = xn+1 − r = g(xn ) − r , en = (xn − r ) and
g 0 (r ) = 0, the truncated Taylor series expansion can be rearranged as,
g 00 (r ) 2
en+1 = en
2
which shows that the error at any step goes down as the square of the
previous step - i.e., quadratically! This manifests itself in the form of
doubling accuracy at every iteration.
f (x) := (x − 2) sin(2x)e−0.8x
0.1 0.2
(a) (c) f ( x ) = ( x − 2 ) 2 sin ( 2x )e− 0.8x
0.05
0.1
0
0
-0.05 deflated root
deflated root
-0.1 f ( x ) = ( x − 2 ) sin ( 2x )e− 0.8x -0.1
0 2 4 6 8 10 -0.2
0 2 4 6 8 10
0.1 0.2
deflated root
deflated root
(b) (d)
0.05
0.1
0
0
-0.05
-0.1
-0.1
g( x ) = f ( x ) ( x − 2 ) g( x ) = f ( x ) ( x − 2 )
0 2 4 6 8 10 -0.2
0 2 4 6 8 10
2.11.1 MATLAB
The MATLAB function for determining roots of a polynomial is called
roots. You can invoke it by entering,
» roots(c)
Note that the function roots finds all of the roots of a polynomial,
including complex ones.
The MATLAB function for finding a real root of any real, single non-
linear algebraic equation (not necessarily a polynomial) is called fzero.
You can invoke it by entering,
» fzero(’fn’,x)
where fn is the name of a m-file that defines the function, x is the initial
guess for the root. This fzero is not based on a very robust algorithm.
If the function you want to solve has singularities, or multiple roots, the
scheme fails to converge, often without producing any appropriate er-
ror or warning messages. Hence use with caution. After it produces an
2.11. SOFTWARE TOOLS 44
2.11.2 Mathematika
Mathematika is another powerful software package for mathematical
analysis including symbolic processing. It also has an inteactive envi-
ronment; i.e., commands, functions are executed as soon as you enter
them. If you invoke Mathematica using a Graphical User Interface (GUI)
then, the ploting functions will display the graphs. Otherwise you are
limited to the use of computational features of Mathematica. A complete
reference to Mathematica can be found in the book by Wolfram (1988).
10 0.05
0
5
-0.05
f(ψ) 0 -0.1
-0.15
-5
-0.2
-10
-4 -2 0 2 4 0 0.1 0.2 0.3 0.4 0.5
ψ ψ
f[psi_]:=Sum[(K[[i]]-1)*z[[i]]/((K[[i]]-1)*psi+1), {i,4}]
Note that no initial guess is needed. Mathematica finds all the three
roots. They are:
{{x -> -1.57727}, {x -> 0.0949203}, {x -> 1.66984}}
Ofcourse, only the second root is of interest. Others do not have any
physical relevance. Note also that while ploting functions, Mathematica
samples the function at sufficient number of data points ( i.e., x-values)
to provide a smooth function. Graphs of the flash equation produced by
Mathematica are shown in figure 2.9.
Component i zi Ki
Carbon dioxide 1 0.0046 1.650
Methane 2 0.8345 3.090
Ethane 3 0.0381 0.720
Propane 4 0.0163 0.390
Isobutane 5 0.0050 0.210
n-Butane 6 0.0074 0.175
Pentanes 7 0.0287 0.093
Hexanes 8 0.0220 0.065
Heptanes+ 9 0.0434 0.036
Table 2.2: Feed composition & equilibrium ratio of a natural gas mixture
in the unknown ψ, which represents the fraction of feed that goes into
the vapor phase.
N
X (1 − Ki )zi
=0 (2.14)
i=1
(Ki − 1)ψ + 1
This equation has several roots, but not all of them have any physical For a bonus point
meaning. Only the root for ψ ∈ [0, 1] is of interest. you may choose to
The test data in Table 2.2, (taken from Katz etal) relate to the flashing find the number of
roots for the test
of a natural gas stream at 1600 psia and 120o F . Determine the fraction
data above!
ψ using the secant algorithm given in figure 2.4 and another root finding
function that is provided in MATLAB named fzero.
" #0.5
To (P12 − P22 )
Qo = 433.54 d2.667 η (2.15)
Po Lσ T
where
h i
[x0 − xn ] (1/S)n+1 − (1/S)
= (2.16)
x0 − yn+1 /K (1/S)n+1 − 1
f (x; p) = 0
h i
(x0 − xn ) (1/S)n+1 − (1/S)
f (x; p) = − =0 (2.17)
(x0 − yn+1 /K) (1/S)n+1 − 1
1. In a typical design problem you might be given the flow rates, (say
L = 10, V = 10), the inlet compositions (say, x0 = 0.8, yn+1 = 0)
and a specified recovery (xn = 0.1615). Your task is to determine
the number of stages (n) required to meet the specifications. Take
the equilibrium ratio to be K = 0.8. Here the unknown variable x
is associated with n and the others form the parameter set. Solve
for n using secant and bisection methods using initial guesses of
[10, 30]. Report the number of iterations required for convergence
to the MATLAB built-in convergence tolerance of eps = 10−16 . You
can use the secant.m and bisect.m algorithms outlined in figures
2.4,2.3. You must construct a m-file to define the function rep-
resented by equation (2.17) in terms of the unknown. Here is a
sample function for the first case.
function f=KBS1(x)
% Kremser-Brown-Souders equation
% number of stages is unknown i.e. solve for x=n
m=length(x);
for i=1:m
n=x(i);
f(i) = (x0-xn)/(x0-ynp1/K) - ( (1/S)ˆ(n+1) - (1/S)) ...
/ ( (1/S)ˆ(n+1) - 1);
end
Make sure that you understand what the above function does! In
the next two parts you will have to modify this function to solve
for a different unknown! Create a file named KBS1.m and enter the
above function. Then to solve the problem from within MATLAB
enter
» secant(’KBS1’,[10,30],eps,1)
2.12. EXERCISE PROBLEMS 49
You may wish to plot the function to graphically locate the root
using
» x=10:1:30;
» y=KBS1(x);
» plot(x,y)
» plot([10:1:30],KBS1(10:1:30))
The phase behavior of fluids can be predicted with the help of equations
of state. The one developed by Peng & Robinson is particularly well
tuned, accurate and hence is widely used. The equation is given below.
RT a(T )
P= − (2.18)
(V − b) V (V + b) + b(V − b)
where
R 2 Tc2 RTc √ p
a(T ) = 0.45724 α(Tr , ω), b = 0.0778 , α = 1 + m(1 − Tr )
Pc Pc
m = 0.37464 + 1.54226ω − 0.26992ω2 , Tr = T /Tc , and Z = P V /RT .
a) Use the function roots(c) in MATLAB to find all the roots of the cubic
equation (2.19) in terms of Z. In MATLAB, how does the function
roots differ from the function fzero?
b) Use the secant method to find the real roots of the above equation.
d) Consider the case where you are given (P , V ) and you are asked to
find T . Develop and implement the Newton iteration to solve for
this case. Use the above equation to compute the temperature of
CO2 in o K at P = 20.684 × 106 P a and V = .04783lit/gmole.
Compare the number of iterations required to obtain a solution to
a tolerance of ||f || < 10−15 using an initial guess of T = 250 by
Newton method with that required by the secant method with an
initial guess of [200,310].
e) Suppose that you are given (T , V ) and you are asked to find P ,
which form of equation will you choose? Eqn. (2.18) or Eqn.(2.19)?
What method of solution would you recommend?
10−5 m2 /s. Determine the time required to cool the solid at a distance
of x = 4cm measured from the exposed surface, to T = 120o C. The
temperature profile as a function of time and distance is given by the
following expression.
h i √
θ = 1 − er f (ξ) − e(hx/k+τ) [1 − er f (ξ + τ)]
(T −Ti ) √x
where the dimensionless temperature, θ = (Ta −Ti ) , and ξ = 2 αt
and
h2 αt
τ= k2
, t is the time, x is the distance and er f is the error function.
L1 v12 L2 v22
f1 (v1 ) = f2 (v2 ) (2.20)
D1 2 D2 2
where v1 , v2 are the velocities in the two pipes and f1 , f2 are the friction
factors given by the Churchill equation.
" #1/12
8 12 1
fi (vi ) = 8 ∗ +
Rei (A + B)1.5
where
16 16
1 37530 D i vi ρ
A = 2.457 ln 0.9
B= and Rei =
(1/Rei ) + 0.27(i /Di ) Rei µ
2.12. EXERCISE PROBLEMS 52
L1 v12 L2 v22
F (v1 ) = f1 (v1 ) − f2 (v2 ) =0
D1 2 D2 2
i.e., for a given guess of v1 , write a m-file that will calculate F (v1 ). Then
carryout the following calculations.
• Solve the problem using secant algorithm with initial guess of [4.5,5.5].
[Ans:v1 = 4.8703]
• Suppose the total flow rate is increased to 0.09 m3 /s, what will be
the new velocities in the pipes.
• Discuss the pros and cons of implementing the Newton method for
this problem.
Mathematics, rightly viewed, possesses not only
truth, but supreme beauty – a beauty cold and aus-
tere, like that of sculpture.
— BERTRAND RUSSELL
Chapter 3
Topics from linear algebra form the core of numerical analysis. Almost
every conceivable problem, be it curve fitting, optimization, simulation
of flow sheets or simulation of distributed parameter systems requiring
solution of differential equations, require at some stage the solution of a
system (often a large system!) of algebraic equations. MATLAB (acronym
for MATrix LABoratory) was in fact conceived as a collection of tools to
aid in the interactive learning and analysis of linear systems and was
derived from a well known core of linear algebra routines written in
FORTRAN called LINPACK.
53
3.1. MATRIX NOTATION 54
A = [aij ], i = 1, · · · , m; j = 1, · · · , n
x = [x1 x2 · · · xn ]
A + B + C = (A + B) + C = A + (B + C)
BC 6= BC
AI = A
AB = I or B = A−1
A2 = AA A3 = AAA = A2 A = AA2
Note that Ap Aq = Ap+q for positve integers p and q. Having extended MATLAB operator
the definition of powers, we can extend the definition of exponential for producing the
from scalars to square matrices as follows. For a scalar α it is, n-th power of a
matrix A is,
α2 X∞
αk Aˆn
α
e =1+α+ + ··· = while the syntax
2 k=0
k! for producing
element-by-
For a matrix A the exponential matrix can be defined as, element power
is,
X∞
A2 Ak A.ˆn.
eA = I + A + + ··· = Make sure that you
2 k=0
k!
understand the
difference between
One operation that does not have a direct counter part in the scalar world
these two
is the transpose of a matrix. It is defined the result of exchanging the operations!
rows and columns of a matrix, i.e.,
MATLAB function
B = A0 ⇒ bij = aji exp(A)
evaluates the
It is easy to verify that exponential
(A + B)0 = A0 + B0 element-by-
element
Something that is not so easy to verify, nevertheless true, is while
expm(A)
(AB)0 = B0 A0 evaluates the true
matrix exponential.
3.2. MATRICES WITH SPECIAL STRUCTURE 57
3.3 Determinant
3. It should also be clear that if all the elements of any row or column
are zero, then the determinant is zero.
4. If every element of any row or column of a matrix is multiplied
by a scalar, it is equivalent to multiplying the determinant of the
original matrix by the same scalar, i.e.,
ka11 ka12 · · · ka1n a11 a12 · · · ka1n
a a22 · · · a2n
21 a21 a22 · · · ka2n
. .. = = k det(A)
. .. .. .. ..
. . . . . .
an1 an2 · · · ann an1 an2 · · · kann
3.3. DETERMINANT 59
Example
Consider the matrix derived in Chapter 1 for the recycle example, viz.
equation (1.8). Let us calculate the determinant of the matrix using the
Laplace expansion algorithm around the first row.
1 0 0.306
det(A) = 0 1 0.702
−2 1 0
1 0.702 0 0.702 0 1
= 1 + (−1)1+2 × 0 × + (−1)1+3 × 0.306 ×
1 0 −2 0 −2 1
= 1 × (−0.702) + 0 + 0.306 × 2 = −0.09
det(A) x1 = det(A(1))
where the matrix A(1) is obtained from A after replacing the first column
with the vector b. i.e.,
b a
1 12
A(1) =
b2 a22
Example
Continuing with the recycle problem (equation (1.8) of Chapter 1), solu-
tion using Cramer’s rule can be implemented with MATLAB as follows:
1 0 0.306 x1 101.48
A x = b ⇒ 0 1 0.702 x2 = 225.78
−2 1 0 x3 0
3.4. DIRECT METHODS 61
where Aik are the cofactors of A. The components of the solution vector,
x are,
x1 = (b1 A11 + b2 A21 + · · · + bn An1 )/det(A)
The right hand side of this system of equations can be written as a vector
matrix product as follows,
x1 A11 A21 ··· An1 b1
x2 A12 A22 ··· An2 b2
1
.. = .. .. ..
det(A) ..
. . . . .
xn A1n A2n · · · Ann bn
or
x =Bb
The above equation can be thought of as the definition for the adjoint
of a matrix. It is obtained by simply replacing each element with its
cofactor and then transposing the resulting matrix.
is given by,
1
d11 0 ··· 0
1
0 ··· 0
d22
D−1 = . ..
.. 0 . 0
1
0 0 ··· dnn
We can develop the algorithm ( i.e., find out the rules) by simply carry-
ing out the matrix multiplication on the left hand side and equating it
3.4. DIRECT METHODS 63
1
vii = i = 1, · · · , n (3.4)
uii
Next, for each of the upper elements (i, j) summing the product of
each element of i-th row of U with the corresponding element of the j-th
column of V , we get,
j
X
uii vij + uir vr j = 0
r =i+1
j
1 X
vij =− uir vr j j = 2, · · · , n; j > i; i = j − 1, 1 (3.5)
uii r =i+1
Example
function v=invu(u)
% Invert upper triangular matrix
% u - (nxn) matrix
% v - inv(a)
for i=2:n
for j=1:i-1
v(i,j)=0;
end
end
for i=1:n
v(i,i)=1/u(i,i);
end
for j=2:n
for i=j-1:-1:1
v(i,j) = -1/u(i,i)*sum(u(i,i+1:j)*v(i+1:j,j));
end
end
x1 + 4x2 = 3
×
1 a12 ċa × a×1, n + 1
ċa
1n
0 1 × a×2, n + 1
?
2n
?
0 0 ċ 1 a×n, n + 1
function x=gauss(a,b)
% Naive Gaussian elimination. Cannot have zeros on diagonal
% a - (nxn) matrix
% b - column vector of length n
for i=1:n
%Step 2: make diagonal elements into 1.0
a(i,i+1:n+1) = a(i,i+1:n+1)/a(i,i);
%return solution
x=a(:,n+1)
Example
Let us continue with the recycle problem (equation (1.8) of Chapter 1).
First we obtain solution using the built-in MATLAB linear equation solver
( viz. x = A\b and record the floating point operations (flops). Then
we solve with the Gaussian elimination function gauss and compare the
flops. Note that in order to use the naive Gaussian elimination function,
we need to switch the 2nd and 3rd equations to avoid division by zero.
The need for pivoting can be illustrated with the following simple exam-
ple.
x1 + x2 = 1
x1 + x2 = 2
1 1
x1 + x2 =
3.4. DIRECT METHODS 70
Next we eliminate the variable x1 from the 2nd equation which resutls
in,
1 1
1− x2 = 2 −
Rearranging this and using back substitution we finally get x2 and x1 as,
1
2−
x2 = 1
1−
1 x2
x1 = −
The problem in computing x1 as → 0 should be clear now. As crosses
the threshold of finite precision of the computation (hardware or soft-
ware), taking the difference of two large numbers of comparable magni-
tude, can result in significant loss of precision. Let us solve the problem
once again after rearranging the equations as,
x1 + x2 = 2
x1 + x2 = 1
and apply Gaussian elimination once again. Since the diagonal element
in the first equation is already unity, we can eliminate x1 from the 2nd
equation to obtain,
1 − 2
(1 − )x2 = 1 − 2 or x2 =
1−
Back substitution yields,
x1 = 2 − x2
Both these computations are well behaved as → 0.
We can actually demonstrate this using the MATLAB function gauss
shown in figure 3.3 and compare it with the MATLAB built-in function
A\b which does use pivoting to rearrange the equations and minimize
the loss of precision. The results are compared in table 3.1 for in
the range of 10−15 to 10−17 . Since MATLAB uses double precision, this
range of is the threshold for loss of precision. Observe that the naive
Gaussian elimination produces incorrect results for < 10−16 .
Since we know where the zero elements are, we do not have to carry out
the elimination steps on those entries of the matrix T ; but the essential
steps in the algorithm remain the same as in the Gaussian elimination
scheme and are illustrated in figure 3.4. MATLAB implementation is
shown in figure 3.5.
Given
d1 c1 0 0 ? b1
a1 ? b2
0 a
d
d2 c2 0
0 0 ?
0 n−2 n−1 cn − 1 bn − 1
? ? ? an − 1 dn bn
STEP 1: Eliminate lower diagonal elements
d1 c1 0 0 ? b1 d(j) = d(j) - {a(j-1)/d(j-1)}*c(j-1)
for j=2:n 0 d 2∗ c2 ? b2∗
0
b(j) = b(j) - {a(j-1)/d(j-1)}*b(j-1)
0
0 ?
0 0 0 d∗n − 1 cn − 1 b∗n − 1
end ? ? ? 0 d∗n b∗n
STEP 2: Back substitution
d1 c1 0 0 ? b1
d2∗ c2 ? b2∗
0
0 for i=n-1:-1:1
0
0 ?
b(i) = {b(i) - c(i)*b(i+1)}/d(i);
end
0 0 0 d∗n − 1 cn − 1 b∗n − 1
? ? ? 0 d∗n b∗n b(n) = b(n)/d(n)
Solution is stored in b
function x=thomas(a,b,c,d)
% Thomas algorithm for tridiagonal systems
% d - diagonal elements, n
% b - right hand side forcing term, n
% a - lower diagonal elements, (n-1)
% c - upper diagonal elements, (n-1)
for i=2:n
fctr=a(i-1)/d(i-1);
d(i) = d(i) - fctr*c(i-1);
b(i) = b(i) - fctr*b(i-1);
end
%return solution
x=b;
L1 A = U1
L2 U1 = U2
L 3 U2 = U 3
L 4 U3 = U 4
3.4. DIRECT METHODS 75
Since the product of all lower triangular matrices is yet another lower
triangular matrix, we can write the above equation as,
LA = U
A = L−1 U = L̂U
3.4.6 LU decomposition
Consider the product of L and U as shown in the expanded form be-
low. All of the elements of L and U are unkonwn. By carrying out the
matrix product on the left hand side and equating element-by-element
to the right hand side, we can develop sufficient number of equations
to find out all of the unkown elements on the left hand side. The trick,
however is, (as we did with inverting a triangular matrix) to carry out the
calculations in a particualr sequence so that no more than one unknown
appears in each equation.
l11 0 0 ··· 0 1 u12 u13 · · · u1n a11 a12 ··· a1n
l
21 l22 0 ··· 0 0 1 u23 · · · u2n a21 a22 ··· a2n
l31 l32 l33 · · · 0 0 0 1 · · · u3n = a31 a32 ··· a3n
. .. ..
. .. .. . .. .. .. . .. ..
. . . . 0 .. . . . . .. . ··· .
ln1 ln2 ln3 · · · lnn 0 0 0 ··· 1 an1 an2 · · · ann
j−1
X
lij = aij − lik ukj j = 2, · · · , n i = j, · · · , n (3.8)
k=1
h Pj−1 i
aji − k=1 ljk uki
uji = j = 2, · · · , n i = j + 1, · · · , n (3.9)
ljj
Ax = b
can be written as
LUx = b ⇒ Ux = L−1 b = b0
and hence
x = U −1 b0
function [L,U]=LU(a)
% Naive LU decomposition
% a - (nxn) matrix
% L,U - are (nxn) factored matrices
% Usage [L,U]=LU(A)
Example
Work through the following exercise in MATLAB to get a feel for the
built-in MATLAB implementation of LU factorization with that given in
figure 3.6. Before you work through the exercise make sure that the file
LU.m that contains the function illustrated in figure 3.6 is in the MATLAB
path. Also, be aware of the upper case function LU of figure 3.6 and the
lower case lu which is the built-in function.
The direct methods discussed in section §3.4 have the advantage of pro-
ducing the solution in a finite number of calculations. They suffer, how-
ever, from loss of precision due to accumulated round off errors. This
problem is particulalry sever in large dimensional systems (more than
10,000 equations). Iterative methods, on the other hand, produce the
result in an asymptotic manner by repeated application of a simple al-
gorithm. Hence the number of floating point operations required to pro-
duce the final result cannot be known a priori. But they have the natural
ability to eliminate errors at every step of the iteration. For an author-
itative account of iterative methods for large linear systems see Young
(1971).
Iterative methods rely on the concepts developed in Chapter 2. They
are extended naturally from a single equation (one-dimensional system)
3.5. ITERATIVE METHODS 79
where the variable xj has been extracted form the j − th equation and
expressed as a function of the remaining variables. The above set of
equations can be applied repetitively to update each component of the
unknown vector x=(x1 , x2 , · · · , xn ) provided an inital guess is known
for x. The above equation can be written in matrix form as, Note that MATLAB
functions
Lx (p) + Dx (p+1) + Ux (p) = b diag
tril
where the matrices D, L, U are defined in term of components of A as triu
follows. are useful in
a11 0 ··· 0 extracting parts of
0 a a given matrix A
22 · · · 0
D= .. ..
. 0 . 0
0 0 · · · ann
0 0 ··· 0 0 a12 · · · a1n
a21 0 ··· 0 0 0 · · · a2n
L=
.. ..
U = .. ..
. . 0 0 0 . .
an1 an2 ··· 0 0 0 ··· 0
which can be rearranged as,
and hence G(x (p) ) = −D−1 (L + U)x (p) + D−1 b and G0 = T = −D−1 (L +
U). This method has been shown to be convergent as long as the original
matrix A is diagonally dominant, i.e.,
3.5. ITERATIVE METHODS 81
n
X
|aii | ≥ aij ı = 1, · · · , n
j=1,j6=i
Observe that known values of the elements in x (p+1) are used on the
right hand side of the above equations (3.15) as soon as they are available
within the same iteration. We have used the superscripts p and (p + 1)
explicitly in equation (3.15) to indicate where the newest values occur.
In a computer program there is no need to assign separate arrays for
p and (p + 1) levels of iteration. Using just a single array for x will
automatically propagate the newest values as soon as they are updated.
The above equation can be written symbolically in matrix form as,
(p+1)
Instead of accepting the value of xj computed from the above for-
mula as the current value, we store it in a temporary variable t and form
(p+1)
a better (or accelerated) estimate of xj from,
where the term in braces represent the Gauss-Seidel scheme. After ex-
tracting x (p+1) from the above equation, it can be cast in the standard
3.5. ITERATIVE METHODS 83
function x=GS(a,b,x,tol,max)
% Gauss-Seidel iteration
% a - (nxn) matrix
% b - column vector of length n
% x - initial guess vector x
% tol - convergence tolerance
% max - maximum number of iterations
% Usage x=GS(A,b,x)
u02 = x 2 − c0 u1
Similarly we have,
u03 = x 3 − c1 u1 − c2 u2
In general we have,
s−1
X u0s
u0s = x s − (uTj · x s ) uj us = s = 2, · · · n; (3.20)
j=1
||u0s ||
3.7. THE EIGENVALUE PROBLEM 86
3 v35 5 p
5
1 v12 2
p1 v34
p2
v46 p6
4 6
3.11.2 MATLAB
3.11.3 Mathematica
Consider laminar flow through the network shown in figure 3.8. The gov-
erning equations are the pressure drop equations for each pipe element
i − j and the mass balance equation at each node.
The pressure drop between nodes i and j is given by,
3.12. EXERCISE PROBLEMS 87
32µlij
pi − pj = αij vij where αij = (3.21)
d2ij
The mass balance at node 2 is given, for example by,
Table 1
Element no 12 23 24 34 35 46
» [ii,jj,s]=find(A)
» S=sparse(ii,jj,s)
Then to solve using the sparse solver and keep flops count,
use
» spy(S)
Repeat the above experiment with the full matrix, A and report
flops.
— ALFRED TENNYSON
Chapter 4
f1 (x1 , x2 , · · · , xn ) = 0
f2 (x1 , x2 , · · · , xn ) = 0
···
fn (x1 , x2 , · · · , xn ) = 0
As with the scalar case, the equation is satisfied only at selected values of
x = r = [r1 , r2 , · · · , rn ], called the roots. The separation process model
discussed in section §1.3.1 (variations 2 and 3, in particular) and the
reaction sequence model of section §1.3.5 are two of the many exam-
ples in chemical engineering that give rise to such non-linear system of
equations. As with the scalar case, the equations often depend on other
parameters, and we will represent them as
f (x; p) = 0 (4.2)
89
4.1. NEWTON’S METHOD 90
f1 (x1 , x2 ) = 0
f2 (x1 , x2 ) = 0
Thus the vectors f (x) = [f1 (x1 , x2 ), f2 (x1 , x2 )] and x = [x1 , x2 ] con-
tain two elements. Let the roots be represented by r = [r1 , r2 ] - i.e.,
f (r) = 0.
Suppose x (0) be some known initial guess for the solution vector x
and let the root be at a small displacement δ from x (0) - i.e.,
r = x (0) + δ
(0) (0) ∂f2
∂f2
0 = f2 (x1 , x2 ) + δ + δ2
∂x1 [x1(0) ,x2(0) ] ∂x2 [x1(0) ,x2(0) ]
1
These are two linear equations in two unknowns [δ1 , δ2 ]. Note that the
two functions [f1 , f2 ] and their four partial derivatives are required to
(0) (0)
be evaluated at the guess value of [x1 , x2 ]. The above equations can
be arranged into matrix form as,
" # " # " #
∂f1 ∂f1
0 f1 δ1
= + ∂x1
∂f2
∂x2
∂f2
0 f2 δ2
∂x1 ∂x2
or in symbolic form
0 = f (0) + J (0) δ
where J (0) is called the Jacobian matrix and the superscript is a reminder
that quantities are evaluated using the current guess value of x (0) . Thus,
the displacement vector δ is obtained by solving the linear system,
δ = −J −1 f
In general then, given x (0) , the algorithm consists of (i) evaluating the
function and the Jacobian at the current iterate x (k) , (ii) solving the linear
system for the displacement vector δ(k) and (iii) finding the new estimate
for the iterate x (k+1) from the equations
Convergence check
The final step is to check if we are close enough to the desired root r
so that we can terminate the iteration. One test might be to check if the
absolute difference between two successive values of x is smaller than
a specified tolerance. This can be done by computing the norm of δ
|δ| ≤
|f | ≤
function x=newton(Fun,Jac,x,tol,trace)
% Newton method for a system of nonlinear equations
% Fun - name of the external function to compute f
% Jac - name of the externan function to compute J
% x - vector of initial guesses
% tol - error criterion
% trace - print intermediate results
%
% Usage newton(’Fun’,’Jac’,x)
%Check inputs
if nargin < 5, trace=0; end
if nargin < 4, tol=eps; trace=0; end
max=25;
n=length(x);
count=0;
f=1;
while (norm(f) > tol & count < max), %check convergence
f = feval(Fun,x); %evaluate the function
J = feval(Jac,x); %evaluate Jacobian
x = x -J\f; %update the guess
count=count+1;
if trace,
fprintf(1,’Iter.# = %3i Resid = %12.5e\n’, count,norm(f));
end
end
r =
2.2262
1.2919
0.8691
0.6399
0.5597
4.1. NEWTON’S METHOD 95
function f=cstrF(x)
% Reactor in series model, the function
% x=[a(1),a(2), .., a(n-1),beta]
% f(i) = beta a(i)ˆ2 + a(i) - a(i-1)
n=length(x);
a0=5.0; an=0.5; %define parameters in equation
function J=cstrJ(x)
% Reactor in series model, the Jacobian
% x=[a(1),a(2), .., a(n-1),beta]
n=length(x);
a0=5.0; an=0.5; %define parameters in equation
J(1,1) = x(n)*2*x(1) + 1;
J(1,n) = x(1)ˆ2;
for i = 2:n-1
J(i,i) = x(n)*2*x(i) + 1;
J(i,i-1) = -1;
J(i,n) = x(i)ˆ2;
end
J(n,n) = anˆ2;
J(n,n-1) = -1;
In the above example, observe first that the number of reactors is defined
implicitly by the length of the vector x. Secondly observe the quadratic
convergence of the iteration sequence - viz. the residual goes down from
10−3 in iteration number 6 to 10−6 in iteration number 7 and 10−12 in
iteration number 8. In other words the number of significant digits of
accuracy doubles with every iteration once the iteration reaches close to
the root.
2 2f ρlij
pi − pj = αij vij where αij = (4.6)
d2ij
In general the friction factor f is given by the Moody chart or its equiv-
alent Churchill correlation. In fully developed turbulent flow it is rel-
atively insensitive to changes in Re. Hence take it to be a constant
f = 0.005.
4.5. EXERCISE PROBLEMS 97
There will be six momentum balance equations, one for each pipe ele-
ment, and three mass balance (for incompressible fluids volume balance)
equations, one at each node. Arrange them as a system of nine equations
in nine unknowns and solve the resulting set of equations. Take the vis-
cosity of the fluid, µ = 0.1P a · s and the density as ρ = 1000kg/m3 . The
dimensions of the pipes are given below.
Table 1
Element no 12 23 24 34 35 46
a) Use MATLAB to solve this problem using Newton method for the
specified pressures of p1 = 300kP a and p5 = p6 = 100kP a. Re-
port the number of iterations and the flops.
— T.H. HUXLEY
Chapter 5
Functional approximations
98
5.1. APPROXIMATE REPRESENTATION OF FUNCTIONS 99
Since the integral does not have a closed form expression, we have to
use a series expansion for,
X∞
2 (−1)k ξ 2k
e−ξ =
k=0
k!
0.0007 0.000025
0.0006 (a)
0.00002 (b) x=0.5
0.0005
error
0.0004 0.000015
0.0003 n=2 4 6 8 0.00001
0.0002 -6
0.0001 5. 10
0 0
0 0.5 1 1.5 2 2 4 6 8 10
x n
1.75
0.01 (c) x=1.0 (d) x=2.0
1.5
0.008 1.25
error
0.006 1
0.75
0.004
0.5
0.002
0.25
0 0
2 4 6 8 10 2 4 6 8 10
n n
Figure 5.1: Error distribution of (x, n) := |er f (x) − P2n+1 (x)| for dif-
ferent levels of truncation
5.1. APPROXIMATE REPRESENTATION OF FUNCTIONS 101
Here the basis functions φi (x) are known functions, chosen with care
to form a linearly independent set and ai are unknown constants that
are to be determined in such a way that we can make Pn (x) as good an
approximation to f (x) as possible - i.e., we can define an error as the
difference between the exact function and the approximate representa-
tion,
(x; ai ) = |f (x) − Pn (x)|
and device a scheme to select ai such that the error is minimized.
Example
So far we have outlined certain general concepts, but left open the choice
of a specific basis functions φi (x), the definition of the norm |.| in the
error or the minimization procedure to get ai .
Let the basis functions be
φi (x) = x i−1 i = 1, · · · n
(b − a)
xk = a + (k − 1) k = 1, · · · , n
(n − 1)
5.1. APPROXIMATE REPRESENTATION OF FUNCTIONS 102
or
n
X
ai xki−1 = f (xk ) k = 1, · · · , n (5.1)
i=1
where the elements of matrix P are given by, Pk,i = xki−1 and the vectors
are a = [a1 , · · · , an ] and f = [f (x1 ), · · · , f (xn )]. Thus we have re-
duced the functional approximation problem to one of solving a system
of linear algebraic equations and tools of chapter 3 become useful!
Let us be even more specific now and focus on approximating the
error function f (x) = er f (x) over the interval x ∈ [0.1, 0.5]. Let us
also choose n = 5 - i.e., a quartic polynomial. This will allow us to write
out the final steps of the approximation problem explicitly. The equally
spaced collocation points are,
function a=erf_apprx(n)
% Illustration functional (polynomial) approximation
% fits error function in (0.1, 0.5) to a
% polynomial of degree n
%define interval
a = 0.1; b=0.5;
by using the function shown in figure 5.2 for increasing degree of poly-
nomials. The matrix P becomes poorly scaled and nearly singular with
increasing degree of polynomial as evidence by computing the determi-
nant of P. For example the determinant of P is 1.60000 × 10−2 for n = 3
and it goes down rapidly to 1.21597 × 10−12 for n = 6. Selecting cer-
tain orthogonal polynomials such as Chebyshev polynomials and using
the roots of such polynomials as the collocation points results in well
conditioned matrices and improved accuracy. More on this in section
§5.8.
Note that MATLAB has a function called polyfit(x,y,n) that will
accept a set of pairwise data {xk , yk = f (xk ) | k = 1, · · · , m} and pro-
duce a polynomial fit of degree n (which can be different from m) using a
least-squares minimization. Try using the function polyfit(x,y,n) for
the above example and compare the polynomial coefficients a produced
by the two approaches.
{(xk , fk ) | k = 1, · · · , m}
T (o F ) P (psia)
220.0000 17.1860
224.0000 18.5560
228.0000 20.0150
232.0000 21.5670
k = (Pn−1 (xk ) − fk ) k = 1, · · · , m
The basis functions are still the set, {x i−1 | i = 1, · · · n} and the poly-
nomial is
Xn
Pn−1 (x) = ai x i−1
i=1
5.2. APPROXIMATE REPRESENTATION OF DATA 106
Observe that the equations are not only linear, but the matrix is also
symmetric. Work through the following example using MATLAB to gen-
erate a quadratic, least-squares fit for the data shown in Table 5.2. Make
sure that you understand what is being done at each stage of the cal-
cualtion. This example illustrates a cubic fit that passes through each of
the four data points, followed by use of the cubic fit to interpolate data
at intermediate temperatures of T = [222, 226, 230]. In the last part the
least squares solution is obtained using the procedure developed in this
section. Finally MATLAB’s polyfit is used to generate the same least
squares solution!
Shift operator
Differential operator
df (x)
Df (x) = = f 0 (x) (5.6)
dx
The difference operators are nothing but rules of calculations, just
like a differential operator defines a rule for differentiation. Clearly these
rules can be applied repeatedly to obtaind higher order differences. For
example a second order forward difference with respect to reference
point i is,
Since the operand fi is the same on both sides of the equation, the op-
erators (which define certain rules and hence have certain effects on the
operand fi ) have an equivalent effect given by,
∆ = (E − 1) or E = (1 + ∆) (5.7)
Equation (5.7) can then be applied on any other operand like fi+k . All
of the operators satisfy the distributive, commutative and associative
rules of algebra. Also, repeated application of the operation can be rep-
resented by,
E α = (1 + ∆)α
5.3. DIFFERENCE OPERATORS 109
Note that E α f (x) simply implies that the function f is evaluated after
shifting the independent variable by α - i.e.,
E α f (x) = f (x + αh)
where we have introduce the inverse of the shift operator E to shift back-
wards. Combining these we can write,
∇fi = fi − E −1 fi = (1 − E −1 )fi
Once again recognizing that the operand fi is the same on both sides of
the equation, the operators are related by,
∇ = (1 − E −1 ) or E −1 = (1 − ∇) or E = (1 − ∇)−1 (5.8)
Yet another relation between the shift operator E and the differential
operator D can be developed by considering the Taylor series expansion
of f (x + h),
h2 00
f (x + h) = f (x) + hf 0 (x) + f (x) + · · ·
2!
which can be written in operator notation as,
" #
h2 D 2
Ef (x) = 1 + hD + + · · · f (x)
2!
E = ehD (5.9)
Now for integer values of α the right hand side is the binomial expansion
while for any real number, it yields an infinite series. Using such an
expansion the above equation can be written as,
α(α − 1) 2 α(α − 1)(α − 2) 3
f (x + αh) = 1 + α∆ + ∆ + ∆ + ···
2! 3!
α(α − 1)(α − 2) · · · (α − n + 1) n
∆ + · · · f (x)(5.10)
n!
Up to this point in our development we have merely used tricks of
operator algebra. We will now make the direct connection to the given,
discrete set of data {(xi , fi ) | i = 1, · · · , m}. Taking x1 as the reference
point, the transformation
x = x1 + αh
x1 f1
∆f1
x2 f2 ∆2f1
∆f2 ∆3f1
x3 f3 ∆2f2 ∆4f1
∆f3 ∆3f2
x4 f4 ∆2f3
∆f4 ∆m-1f1
x5 f5
∆4fm-4
∆3fm-3
xm-1 fm-1 ∆2fm-2
∆fm-1
xm fm
The polynomial in equation (5.11) will pass through the given data set
{(xi , fi ) | i = 1, · · · , m} - i.e., for integer values of α = 0, 1, · · · (m − 1)
it will return values of {f1 , f2 , · · · fm }. This implies that the residual
function R(x) will have roots at the data points {xi | i = 1, · · · , m}. For
a polynomial of degree (m − 1), shown in equation (5.11), the residual at
other values of x is typically represented as R(x) ≈ O(hm ) to suggest
that the leading term in the truncated part of the series is of order m.
Example
A set if five (m = 5) equally spaced data points and the forward differ-
ence table for the data are shown in figure 5.4. For this example, clearly
h = 1 and x = x1 + α. We can take the reference point as x1 = 2 and
construct the following linear, quadratic and cubic polynomials, respec-
tively. Note that
P4 (2 + α) =
P3 (2 + α) for this
case! Why?
5.3. DIFFERENCE OPERATORS 112
x1 = 2 f1 = 8
∆f 1 = 19
x2 = 3 f 2 = 27 ∆2 f 1 = 18
∆f 2 = 37 ∆3 f 1 = 6
x3 = 4 f 3 = 64 ∆2 f 2 = 24 ∆4 f 1 = 0
∆f 3 = 61 ∆3 f 2 = 6
x4 = 5 f 4 = 125 ∆2 f 3 = 30
∆f 4 = 91
x5 = 6 f 5 = 216
x = x0 + αh
makes α the new independent variable and for negative integer values
of α = −1, · · · − n we retrieve the equally spaced data set {x−1 , · · · x−n }
and for non-integer (real) values of α we can reach the other values of
x ∈ (x−n , x0 ). Splitting equation (5.12) into two parts,
α(α + 1) 2 α(α + 1)(α + 2) 3
f (x0 + αh) = 1 + α∇ + ∇ + ∇ + ···
2! 3!
α(α + 1)(α + 2) · · · (α + n − 1) n
∇ + · · · f (x0 ) + R(x)
n!
we can recognize the terms in the square brackets as a polynomial of
degree n in the transformed variable α. We still need to determine
the numbers {∇f (x0 ), ∇2 f (x0 ), · · · , ∇n f (x0 )}. These can be computed
and organized as a backward difference table shown in figure 5.5. Since
backward differences are needed for constructing the polynomial, it is
called the Newton backward difference polynomial and it is given by,
α(α + 1) 2 α(α + 1)(α + 2) 3
Pn (x0 + αh) = 1 + α∇ + ∇ + ∇ + ···
2! 3!
α(α + 1)(α + 2) · · · (α + n − 1) n
∇ f (x0 ) + O(hn+1 ) (5.13)
n!
The polynomial in equation (5.13) will pass through the given data set
{(xi , fi ) | i = 0, · · · , −n} - i.e., for integer values of α = 0, −1, · · · − n it
will return values of {f0 , f−1 , · · · f−n }. At other values of x the residual
will be of order O(hn+1 ).
5.3. DIFFERENCE OPERATORS 114
x− 4 f − 4
∇f − 3
x− 3 f − 3 ∇2 f − 2
∇f − 2 ∇3 f − 1
x− 2 f − 2 ∇2 f − 1 ∇4 f 0
∇f − 1 ∇3 f 0
x− 1 f − 1 ∇2 f 0
∇f 0
x0 f 0
x− 4 = 2 f −4 = 8 ? ? ? ? ?
? ? ∇f − 3 = 19 ? ? ? ?
x− 3 = 3 f − 3 = 27 ? ∇2 f − 2 = 18 ? ? ?
x
? NBF
ar?
ound -2 ∇f − 2 = 37 ? ? ∇ f −1 = 6
3 ?
x− 2 = 4 f − 2 = 64 ? ∇ f − 1 = 24
2 ? ? ∇ f0 = 0
4
? NFF aro
? und x-2 ∇f − 1 = 61 ? ? ∇ f0 = 6
3 ?
x− 1 = 5 f − 1 = 125 ? ∇ f 0 = 30
2 ? ? ?
? ? ∇f 0 = 91 ? ? ? ?
x0 = 6 f 0 = 216 ound ?x 0 ? ? ? ?
ar
NBF
Example
A set if five (n = 4) equally spaced data points and the backward differ-
ence table for the data are shown in figure 5.6. This is the same example
as used in the previous section! It is clear that h = 1 and x = x0 + α.
In the previous case we constructed a linear, quadratic and cubic poly-
nomials, with x3 = 4 as the reference point. In the present case let us
use the same reference point, but it is labelled as x−2 = 4. A quadratic
backward difference polynomial in α is,
α(α + 1)
P2 (4 + α) = (64) + α(37) + (18) + O(h3 )
2!
which passes through the points (x−2 , f−2 ), (x−3 , f−3 ) and (x−4 , f−4 )
for α = 0, −1, −2, respectively. Recall that the forward difference poly-
nomial around the same point was, Calculate the
interpolated value
α(α − 1) of f (4.5) from
P2 (4 + α) = (64) + α(61) + (30)
2! these two
polynomials
which passes through the three forward point for α = 0, 1, 2. Although
they are based on the same reference point, these are two different poly-
nomials passing through a different set of data points.
As a final example, let us construct a quadratic backward difference
polynomial around x0 = 6. It is, Is this polynomial
different from the
α(α + 1) NFF, P2 (4 + α)
P2 (6 + α) = (216) + α(91) + (30)
2! constructed above?
5.4. INVERSE INTERPOLATION 116
150
125
f(x=?)=100
100
f(x) 75
P2
(4+
(spurious root)
(desired root)
x=0.286962
x=4.64637
α)
50
25
f(x) = x3
0
-2 0 2 4 6
x
Then we let f (x1 + αh) = d and rearrange the polynomial in the form
αi+1 = g(αi ) i = 0, 1, 2 · · ·
and the initial guess obtained by truncating the polynomial after the
linear term,
d − f1
α0 =
∆f1
Example
Continuing with the task of finding x where f (x) = 100 for the data
shown in figure 5.4, the fixed point iterate is,
d − f1 100 − 64
α0 = = = 0.5902
∆f1 61
The first ten iterates, produced from the m-file given below,
5.5. LAGRANGE POLYNOMIALS 118
i αi
1 .59016393
2 .64964028
3 .64613306
4 .64638815
5 .64636980
6 .64637112
7 .64637102
8 .64637103
9 .64637103
10 .64637103
function a=g(a)
for i=1:10
fprintf(1,’%2i %12.7e\n’,i,a);
a=(100 - 64 - 15*a*(a-1))/61;
end
where
n
Y x − xj
δi (x) =
xi − x j
j=0,j6=i
Note that (
0 j 6= i
δi (xj ) =
1 j=i
5.5. LAGRANGE POLYNOMIALS 119
x0 = 1.0 f 0 = 1.000
f[ x0 , x1 ] = 3.6400
x1 = 1.2 f 1 = 1.728 f[ x0 , x1 , x2 ] = 3.700
f[ x1 , x2 ] = 5.4900 f[ x0 , x1 , x2 , x3 ] = 1.000
x2 = 1.5 f 2 = 3.375 f[ x1 , x2 , x3 ] = 4.300
f[ x2 , x3 ] = 7.2100
x3 = 1.6 f 3 = 4.096
Example
Consider the example data and the divided difference table shown in fig-
ure 5.8. If we wish to construct a quadratic polynomial passing through
(x0 , f0 ), (x1 , f1 ), (x2 , f2 ) for example using equation (5.14), it will be
The same polynomial using equation (5.15) and the difference table shown
in figure 5.8 will be written as,
function f=LagrangeP(xt,ft,x)
% (xt,ft) are the table of unequally spaced values
% x is where interpolated values are required
% f the interpolated values are returned
m=length(x);
nx=length(xt);
ny=length(ft);
if (nx ˜= ny),
error(’ (xt,ft) do not have the same # values’)
end
for k=1:m
sum = 0;
for i=1:nx
delt(i)=1;
for j=1:nx
if (j ˜= i),
delt(i) = delt(i)*(x(k)-xt(j))/(xt(i)-xt(j));
end
end
sum = sum + ft(i) * delt(i) ;
end
f(k)=sum;
end
cepts a table of values (xt, f t), constructs the highest degree Lagrange
polynomial that is possible and finally evaluates and returns the inter-
polated values of the function y at specified values of x.
that passes through the given data set {(xi , fi ) | i = 1, · · · , m}. Note
that the independent variable x has been transformed into α using x =
x1 + αh, hence dx/dα = h. Now, the first derivative is obtained as,
0 df dPm−1 dPm−1 dα 1 α + (α − 1) 2
f (x) = ≈ = = ∆+ ∆ +
dx dx dα dx h 2
{α(α − 1) + (α − 1)(α − 2) + α(α − 2)} 3
∆ + · · · f (x1 )(5.16)
6
Equation (5.16) forms the basis of deriving a class of approximations for
first derivatives from a tabular set of data. Note that the equation (5.16)
is still a function in α and hence it can be used to evaluate the derivative
at any value of x = x1 + αh. Also, the series can be truncated after
any number of terms. Thus, a whole class of successively more accurate
representations for the first derivative can be constructed from equa-
tion (5.16) by truncating the series at higher order terms. For example
5.6. NUMERICAL DIFFERENTIATION 123
E = ehD or hD = ln E = ln (1 + ∆)
∆2 ∆3 ∆4
hD = ∆ − + − + ···
2 3 4
Operating both sides with f (x1 ) ( i.e., using x1 as the reference point),
we get,
" #
0 1 ∆2 ∆3 ∆4
Df (x1 ) = f (x1 ) = ∆− + − + · · · f (x1 ) (5.17)
h 2 3 4
1
f 0 (x1 ) = [∆f (x1 )] + O(h)
h
1
= [f2 − f1 ] + O(h)
h
which is a 2-point, first order accurate, forward difference approximation
for first derivative at x1 . Truncating the series after the first two terms
(m = 3),
1 1
f 0 (x1 ) = ∆f (x1 ) − ∆2 f (x1 ) + O(h2 )
h 2
1 1
= (f2 − f1 ) − (f1 − 2f2 + f3 ) + O(h2 )
h 2
1
= [−3f1 + 4f2 − f3 ] + O(h2 )
2h
which is the 3-point, second order accurate, forward difference approx-
imation for the first derivative at x1 . Clearly both are approximate rep-
resentations of the first derivative at x1 , but the second one is more
accurate since the truncation error is of the order h2 .
Note that while, equation (5.17) is evaluated at the reference point
on both sides of the equation, the earlier equation (5.16) is a polynomial
that is constructed around the reference point x1 , but can be evaluated at
5.6. NUMERICAL DIFFERENTIATION 124
This equation can also be obtained directly using equation (5.9) as,
1 h 2 i 1
f 00 (x1 ) = 2
∆ f (x 1 ) = 2 (f1 − 2f2 + f3 ) + O(h)
h h
1 h 2 i
f 00 (x1 ) = 2
∆ f (x1 ) − ∆3 f (x1 )
h
1
= (2f1 − 5f2 + 4f3 − f4 ) + O(h2 )
h2
Note that the third order term turns out to be zero and hence this for-
mula turns out to be more accurate. This is a 3-point, second order ac-
curate central difference approximation for the second derivative given
as,
1 h i 1
f 00 (x2 ) = 2 ∆2 f (x1 ) = 2 (f1 − 2f2 + f3 ) + O(h2 )
h h
5.7. NUMERICAL INTEGRATION 126
One can derive finite difference approximations from Taylor series ex-
pansion also. Consider the following expansions around xi .
h2 00 h3 000
f (xi + h) = f (xi ) + hf 0 (xi ) + f (xi ) + f (xi ) + · · ·
2 3!
h2 00 h3 000
f (xi − h) = f (xi ) − hf 0 (xi ) + f (xi ) − f (xi ) + · · ·
2 3!
Subtracting the second from the first equation, and extracting f 0 (xi ), we
get,
f (xi + h) − f (xi − h) h2 00
f 0 (xi ) = − f (xi ) + · · ·
2h 6
or,
fi+1 − fi−1
f 0 (xi ) = + O(h2 )
2h
which is a central difference formula for the first derivative that we de-
rived in the last section §5.6. Adding the two Taylor series expansions
above, we get,
h4 0000
fi+1 + fi−1 = 2fi + h2 f 00 (xi ) + f (xi ) + · · ·
12
or,
1
f 00 (xi ) = [fi+1 + fi−1 − 2fi ] + O(h2 )
h2
which is a central difference formula for the second derivative that we
derived in the last section §5.6.
with an error of order hn+1 , we can use this approximation to carry out
the integration. We first divide the interval x ∈ [a, b] into n subdivisions
as shown in the sketch below; hence there will be
f(x)
f1 f
2 fi
x=b
x=-a
1 2 i n-1
i=0 i=n
h = (b − a)/n, x = x0 + αh dx = hdα
or,
Z x1 Z1
f (x)dx ≈ [1 + α∆] f0 h dα + O(h3 )
x0 0
This formula is the well known trapezoidal rule for numerical integra-
tion. The geometrical interpretation is that it represents the shaded area
under the curve. Note that while numerical differentiation, as developed
in equation (5.16), lowers the order of the truncation error by one due to
the term dα/dx = 1/h numerical integration increases the order of the
5.7. NUMERICAL INTEGRATION 128
truncation error by one due to the term dx = hdα. In the above formula
the truncation error is of order O(h3 ). It is called the local truncation
error since it is the error in integrating over one interval x ∈ (x0 , x1 ).
To obtain the complete integral over the interval x ∈ [a, b] we apply
equation (5.21) repeatedly over each of the subdivisions as,
Zb n Z xi
X Xn X n
h
f (x)dx = f (x)dx = [fi−1 + fi ] + O(h3 )
a
i=1
xi−1
i=1
2 i=1
| {z }
global error
Zb n
hX
f (x)dx = [fi−1 + fi ] + O(h2 ) (5.22)
a 2 i=1 | {z }
global error
or,
Z x2 Z2
α(α − 1) 2
f (x) dx ≈ 1 + α∆ + ∆ f0 h dα + O(h4 )
x0 0 2
Note that the next neglected term in the polynomial P2 (x0 + αh) that
corresponds to order O(h3 ) term viz.
Z2
α(α − 1)(α − 2)) 3
∆ f0 h dα
0 3!
turns out to be exactly zero, thus making the local truncation error in
the Simpson’s rule to be actually of order O(h5 ) Repeated application of
5.7. NUMERICAL INTEGRATION 129
Zb
h
f (x)dx = [f0 + 4f1 + 2f2 + 4f3 + 2f4 + · · · + fn ] + O(h4 )
a 3 | {z }
global error
(5.24)
Note that in applying Simpson’s rule repeatedly over the interval x ∈
[a, b], we must have an even number of intervals (n even) or equivalently
an odd number of points.
I = I(h1 ) + E(h1 )
where I(h1 ) is the approximate estimate of the integral using grid size
of h1 and E(h1 ) is the error. Similarly we have,
I = I(h2 ) + E(h2 )
E(h1 ) h2
= 12
E(h2 ) h2
or,
h21
I(h1 ) + E(h2 ) = I(h2 ) + E(h2 )
h22
which can be solved to obtain E(h2 ) as,
I(h1 ) − I(h2 )
E(h2 ) =
1 − (h1 /h2 )2
5.7. NUMERICAL INTEGRATION 130
1
I = I(h2 ) + [I(h2 ) − I(h1 )]
(h1 /h2 )2 − 1
If h2 = h1 /2 then we have,
1
I = I(h2 ) + [I(h2 ) − I(h1 )]
22 − 1
3.5
3
2.5
2
f(x)
1.5
1
0.5
0
0 0.2 0.4 0.6 0.8
x
O ( h2 ) O ( h4 ) O ( h6 )
(k = 1) (k = 2) (k = 3)
j = 1 h = 0.8 0.1728 1.3674667 1.64053334
j = 2 h = 0.4 1.0688 1.6234667 1.64053334
j = 3 h = 0.2 1.4848 1.6394667
j = 4 h = 0.1 1.6008
function f=int_ex(x)
%defines a 5th degree polynomial
m=length(x);
for i=1:m
f(i) = 0.2 + 25*x(i) - 200*x(i)ˆ2 + ...
675*x(i)ˆ3 - 900*x(i)ˆ4 + 400*x(i)ˆ5;
end
MATLAB example
— G.M. TREVELYAN
Chapter 6
dy
= f (y, t) (6.1)
dt
y(t = t0 ) = y 0 (6.2)
133
6.1. MODEL EQUATIONS AND INITIAL CONDITIONS 134
dn θ dn−1 θ dθ
an + a n−1 + · · · a1 + a0 θ = b (6.3)
dt n dt n−1 dt
subject to a set of n initial conditions at t0 of the form,
dn−1 θ
= cn−1
dt n−1 t0
dn−2 θ
= cn−2
dt n−2 t0
.. .
. = .. (6.4)
dθ
= c1
dt t0
θ|t0 = c0
Since all of these conditions are given at t0 , this remains an initial value
problem. Equation (6.3) can be recast into a system of n first order equa-
tions of the form (6.1) as follows. Let us define θ and all of its (n − 1)
successive higher derivatives as
dθ d2 θ dn−1 θ
y1 (t) = θ(t), y2 (t) = , y3 (t) = , ··· yn (t) =
dt dt 2 dt n−1
Then we have,
dy1
= y2 , y1 (t0 ) = c0
dt
dy2
= y3 , y2 (t0 ) = c1
dt
.. .
. = .. (6.5)
dyn−1
= yn , yn−1 (t0 ) = cn−2
dt
dyn 1
= [b − a0 y1 − a1 y2 − · · · − an−1 yn ], , yn (t0 ) = cn−1
dt an
6.2. TAYLOR SERIES EXPANSION 135
where the last equation has been obtained from the n-th order equation
(6.3). Also shown in equations (6.5), are the transformed initial condi-
tions from equation (6.4) in terms of the new variable set y.
Note that the coefficients {a0 , a1 , · · · an , b} in equation (6.3) can in
general be nonlinear functions of θ and its derivatives. This nonlinearity
will reflect in equations (6.5),since the coefficients {a0 , a1 , · · · an , b} will
be functions of the transformed variables {y1 , y2 · · · yn }.
dy
= f (y), y(t0 ) = y0 (6.6)
dt
h2
y(tn + h) = y(tn ) + y 0 (tn )h + y 00 (tn ) + ···
2
Truncating after the linear term and recognizing that y 0 (tn ) = f (yn ),
we have the Euler scheme for generating the solution sequence,
where tn has been used as the reference point, fn means f (yn ) and h
is the step size. Since t = tn + αh we have dt = hdα. Using a one term
expansion in equation (6.8), ( i.e., m = 0) results in,
Z tn+1 Z tn+1
yn+1 − yn = P0 (tn + αh)dt + O(h)dt
tn t
| n {z }
local truncation error
Z1 Z1
= P0 (tn + αh) hdα + O(h)hdα
0 0
Z1
= fn hdα + O(h2 )
0
= fn h + O(h2 )
which is the same equation as (6.7). This approach, however, lends itself
naturally to further development of higher order methods. For example
a two-term expansion ( i.e., m = 1) results in,
Z tn+1 Z tn+1
yn+1 − yn = P1 (tn + αh)dt + O(h2 )dt
tn t
| n {z }
local truncation error
Z1 Z1
= P1 (tn + αh) hdα + O(h2 )hdα
0 0
Z1
= [fn + α∆fn ] hdα + O(h3 )
0
" #1
α2
= h α fn + ∆fn + O(h3 )
2 0
1
= h fn + (fn+1 − fn ) + O(h3 ).
2
6.2. TAYLOR SERIES EXPANSION 137
Hence we have the final form of the modified Euler scheme as,
h
yn+1 = yn + [fn + fn+1 ] + O(h3 ) n = 0, 1, · · · (6.9)
2 | {z }
local error
Both the Euler method given in equation (6.7) and the modified Euler
scheme given by equation (6.9) are single-step methods since only yn
is required to predict yn+1 . The modified Euler method is an implicit
scheme since we need to compute fn+1 which depends on yn+1 . Note
that implicit schemes requires the solution of a nonlinear algebraic equa-
tion at every time step. Thus to calculate yn+1 from equation (6.9) we
need to use an iterative method that involves providing an initial guess
for yn+1 and using equation (6.9) as a fixed point iteration scheme until
yn+1 converges to desired accuracy. At a first glance, this might appear
to be a disadvantage of the implicit schemes. However, implicit schemes
have the ability to anticipate sharp changes in the solution between yn
and yn+1 and hence are suitable (in fact required) for solving the so
called stiff differential equations.
This initial guess could be provided by the Euler method ( viz. equa-
tion (6.7)). When an explicit scheme is combined with an implicit scheme
in this manner, we have the so called predictor-corrector scheme. The
Euler and modified Euler predictor-corrector pair is,
P C hh P
i
yn+1 = yn + hf (yn ) and yn+1 = yn + f (yn ) + f (yn+1 )
2
(6.10)
where the superscript P represents the predicted value from an explicit
scheme and C represents the corrected value from an implicit scheme.
It should be clear that extending the Newton forward polynomial to
a three-term expansion will not be fruitful, since that would involve not
only fn+1 , but also fn+2 . We can, however, use Newton backward poly-
nomials to develop higher order methods as will be done in section §6.3.
But, let us explore first the reason for and the circumstances under which
implicit schemes are useful.
dy
= λ y, y(t = 0) = 1
dt
6.2. TAYLOR SERIES EXPANSION 138
k x
t
d2 x dx
m +k + cx = 0
dt 2 dt
m 2 c
λ +λ+ =0
k k
6.2. TAYLOR SERIES EXPANSION 140
p
−1 ± 1 − 4mc/k2
λ=
(2m/k)
k c
λ1 = − and λ2 = −
m k
where the fast and slow response terms are as shown. The sketch in
figure 6.1 also shows the fast and slow response solutions. Note that if
m = 0, the order of the differential equation drops by one and λ1 is the
only time scale for the problem. This kind of phenomena also occurs
in a number of chemical reaction systems, where some of the reactions
can occur on a rapid time scale while others take place on a longer time
scale. The ozone decomposition model discussed in section §1.4.2 is
another example of stiff differential equations.
It should now be clear that stiffness phenomena corresponds to large
eigenvalues and fast response regions where the solution changes rapidly.
In a system of n first order equations there will be n characteristic roots
or eigenvalues. If λmax is the largest eigenvalue, then explicit schemes
will typically have a numerical stability limit of the form |hλmax | <
constant. Hence explicit schemes require that extremely small step
size h be used in regions where the system responds very rapidly; oth-
erwise the integration sequence will diverge. Implicit schemes that are
absolutely stable have no such restrictions. The integration sequence
using implicit schemes will remain bounded. The choice of step size is
determined only by the desired accuracy of the solution. Stability analy-
sis for a variety of explicit and implicit methods are discussed in greater
detail by Lapidus and Seinfeld (1971).
6.3. MULTISTEP METHODS 141
h
yn+1 = yn + [23 fn − 16 fn−1 + 5 fn−2 ] + O(h4 ) n = 2, 3, 4, · · ·
12 | {z }
local error
(6.11)
The following points should be observed on the above equation.
The next higher order scheme can be developed from a four-term ex-
pansion ( i.e., m = 3) . This is called 5-th order Adams-Bashforth scheme.
viz.
Z tn+1 Z tn+1
yn+1 − yn = P3 (tn + αh)dt + O(h4 )dt
tn t
| n {z }
local truncation error
Z1 Z1
= P3 (tn + αh) hdα + O(h4 )hdα
0 0
Z1
α(α + 1) 2 α(α + 1)(α + 2) 3
= fn + α∇fn + ∇ fn + ∇ fn hdα + O(h5 )
0 2! 3!
1 5 2 3 3
= h fn + ∇fn + ∇ fn + ∇ fn + O(h5 )
2 12 8
which can be rearranged into the form,
h
yn+1 = yn + [55 fn − 59 fn−1 + 37 fn−2 − 9fn−3 ] + O(h5 ) n = 3, 4, · · ·
24 | {z }
local error
(6.12)
In this manner fn+1 is introduced on the right hand side. This class
of implicit schemes are called Adams-Moulton schemes. We are still
integrating one step from tn to tn+1 . Since t = tn+1 + αh and the limits
of integration in α become (−1, 0). A four-term expansion results in,
Z tn+1 Z tn+1
yn+1 − yn = P3 (tn+1 + αh)dt + O(h4 )dt
tn t
| n {z }
local truncation error
Z0 Z0
= P3 (tn + αh) hdα + O(h4 )hdα
−1 −1
Z0
α(α + 1) 2 α(α + 1)(α + 2) 3
= fn+1 + α∇fn+1 + ∇ fn+1 + ∇ fn+1 hdα + O(h5
−1 2! 3!
1 1 2 1 3
= h fn+1 − ∇fn+1 − ∇ fn+1 − ∇ fn+1 + O(h5 )
2 12 24
h
yn+1 = yn + [9 fn+1 + 19 fn − 5 fn−1 + fn−2 ] + O(h5 ) n = 2, 4, · · ·
24 | {z }
local error
(6.13)
The pair of explicit-implicit schemes given by (6.12,6.13) respectively can
be used as a predictor-corrector pair.
possible to double
step size
y0 } y1 y2 y3 y4 y5 y6
given
begin using
generate using
Adams scheme
other methods
tolerance, then we must halve the step size and repeat the calculation
for that step. In so doing, we need to generate intermediate values at
intervals of (h/2). For example if the result for y7 does not meet the
tolerance, then we repeat the calculation from y6 with a step size of
h/2. We need to generate intermediate values at y4.5 and y5.5 . This can
be done using the Newton backward interpolation polynomials; but the
truncation errors in the interpolating polynomials should be of the same
order and the Adams scheme. Specifically the interpolation rules are:
1
yn− 1 = [35yn + 140yn−1 − 70yn−2 + 28yn−3 − 5yn−4 ]
2 128
1
yn− 3 = [−yn + 24yn−1 + 54yn−2 − 16yn−3 + 3yn−4 ]
2 64
Example
MATLAB has several built-in functions for solving initial value problems.
The functions named ADAMS and GEAR, use multistep methods. All of
the ODE solvers in MATLAB are part of the SIMULINK toolbox. Hence
the m-files that define the problem must have a special structure. In
this section we illustrate how to use these functions to solve the ozone
decomposition model. Recall that the equations are,
dy1
= f1 (y1 , y2 ) = −y1 − y1 y2 + κy2
dt
dy2
= f2 (y1 , y2 ) = (y1 − y1 y2 − κy2 )/
dt
The initial compositions are y(t = 0) = [1.0, 0.0]. The parameters are
= 1/98 and κ = 3.0. The equations are clearly nonlinear. The m-file
6.4. RUNGE-KUTTA METHODS 145
function [ydot,y0]=ozone(t,y,u,flag)
k=3.0;epsilon=1/98;
if abs(flag) == 1
ydot(1) = -y(1) - y(2)*y(1) + k*epsilon*y(2);
ydot(2) = (y(1)-y(1)*y(2)-epsilon*k*y(2))/epsilon;
elseif flag == 0
ydot=[2,0,0,0,0,0]; %first element=number of equations
y0=[1 0]; %initial conditions
else
ydot=[];
end
The independent variable t and the solution y at the same time values
are returned in the corresponding varaibles. These results are shown
graphically in figure 6.4. Observe that y2 (t) increases rapidly from an
initial condition of zero and hence the system is very stiff during the
early times.
1.00
y1
0.75 y2
y1 or y2
0.50
0.25
0
0 1 2 3
time
the same goal in a single step, but at the expense of requiring many
function evaluations per step. Being single-step schemes, they are self-
starters. They are also classified as explicit, semi-implicit and implicit
schemes. Implicit schemes require solution of a set on non-linear alge-
braic equations at every time step, but they are suitable for stiff differ-
ential equations.
v
X
yn+1 = yn + w i ki (6.14)
i=1
i−1
X
ki = h f tn + ci , yn + aij kj , c1 = 0, i = 1, 2, · · · v
j=1
0
c2 a21
c3 a31 a32
c4 a41 a42 a43
w1 w2 w3 w4
or
c A
w
yn+1 = yn + w1 k1 (6.15)
k1 = h f (tn , yn )
or
yn+1 = yn + w1 h f (tn , yn )
The procedure to determine w1 is to match the above equaiton with the
Taylor series expansion,
h2 00 h3 000
yn+1 = yn + hyn0 + y + y + ··· (6.16)
2 n 3! n
The first term on the right hand side is the same in both equations.
Recongnizing that y 0 = f the second term will also match if we make
w1 = 1 and this results in recovering the Euler scheme developed in
equation (6.7). We cannot match with any higher order terms and hence
the local truncation error is of order O(h2 ).
yn+1 = yn + w1 k1 + w2 k2 (6.17)
k1 = h f (tn , yn )
k2 = h f (tn + c2 h, yn + a21 k1 )
6.4. RUNGE-KUTTA METHODS 148
This scheme has four unknown paramters {w1 , w2 , c2 , a21 } which must
be determined by matching the Taylor series expansion of equation (6.17)
with the equation (6.16). Expanding equation (6.17) we get,
or,
" #
∂f ∂f
yn+1 = yn + w1 h fn + w2 h f + (c2 h) + a21 (hf ) + ···
∂t ∂y n
(6.18)
Substituting for y 0 and its higher derivatives in terms of f in equation
(6.16) and expanding, we get,
h2 df
yn+1 = yn + hfn + + O(h3 )
2 dt
or " #
h2 ∂f ∂f ∂y
yn+1 = yn + hfn + + + O(h3 ) (6.19)
2 ∂t ∂y ∂t
Now comparing the fn terms between equations (6.18) and (6.19) we
require that
w1 + w 2 = 1
∂f
for the two equations to match. Next comparing ∂t terms, we require,
w2 c2 = 1/2
∂f ∂y
Finally comparing ∂y ∂t we require,
w2 a21 = 1/2
Thus, we have matched all terms of order O(h2 ) leaving a truncation er-
ror or order O(h3 ). In that process we have developed 3 constraint equa-
tions on the four unknonws {w1 , w2 , c2 , a21 } appearing in the 2-stage
RUnge-Kutta scheme (6.17). Any choice of values for {w1 , w2 , c2 , a21 }
that satisfies the above three constraints will result in a 3-rd order, 2-
stage Runge-Kutta scheme. Since there are four variables and only three
equations, we have one extra degree of freedom. Hence the solution is
not unique. Two sets of results are:
and
w1 = 1/2, w2 = 1/2, c2 = 1, a21 = 1
6.4. RUNGE-KUTTA METHODS 149
The later is the equivalent of the predictor-corrector pair using Euler and
modified Euler schemes developed in equations (6.10). In summary this
scheme is a 2-stage RK method since it requires two function evaluations
per step. It is explicit and has a local truncation error of O(h3 ).
Using the first set of parameter values in equation (6.17), we have,
2 2
yn+1 = yn + k1 + k2
3 3
k1 = h f (tn , yn )
3 3
k2 = h f (tn + h, yn + k1 )
2 2
or in tabular form,
0
3/2 3/2
2/3 2/3
0
1/2 1/2
1/2 0 1/2
1 0 0 1
1/6 2/6 2/6 1/6
1
yn+1 = yn + [k1 + 2k2 + 2k3 + k4 ] (6.20)
6
k1 = h f (tn , yn )
h k1
k2 = h f (tn + , yn + )
2 2
h k2
k3 = h f (tn + , yn + )
2 2
k4 = h f (tn + h, yn + k3 )
Embedded forms
k1 0
1 1
k2 4 4
3 3 9
k3 8 32 32
12 1932 7200 7296
k4 13 2197 − 2197 2197
439 3680 −845
k5 1 216 −8 513 410
yn+1 = yn + w1 k1 + w2 k2 (6.22)
6.4. RUNGE-KUTTA METHODS 151
c1 a11 a12
c2 a21 a22
w1 w2
While the fully-implicit forms of the last section §6.4.4, have desirable
stability properties, they are computationally demanding since a system
of non-linear algebraic equations must be solved iteratively at every time
step. In an effort to reduce the computational demand while retaining
the stability characteristics, Rosenbrock (1963) proposed a special form
of the algorithm. These are suitable for autonomous system of equations
of the form,
dy
= f (y) y(t = t0 ) = y 0
dt
A 2-stage, 3-rd order scheme is shown below.
y n+1 = y n + w1 k 1 + w2 k 2 (6.23)
−1
k1 = h [I − ha1 J(y n )] f (y n )
k2 = h [I − ha2 J(y n + c1 k1 )]−1 f (y n + b1 k1 )
6.5. DYNAMICAL SYSTEMS THEORY 152
w1 = −0.41315432, w2 = 1.41315432
√ p √
−6 − 6 + 58 + 20 6
b1 = c1 = √
6+2 6
∂f
Here J = ∂ y is the Jacobian, which must be evaluated at every time
step. Note that the main advantage in using equation (6.23) is that k1 , k2
could be computed without the need for iteration, although it requires
two matrix inverse computations per step.
Chapter 7
Consider the model for heat transfer through a fin developed in section
§1.5.1. We will consider three specific variations on this model equation
(1.22) and the associated boundary conditions. First let us scale the
problem by introducing the following dimensionless temperature and
153
7.1. MODEL EQUATIONS AND BOUNDARY CONDITIONS 154
distance variables,
T − T∞ x
θ= ξ=
T0 − T ∞ L
Using these definitions, equation (1.22) can be rewritten as,
" #
d dθ
kA − hP L2 θ = 0 (7.1)
dξ dξ
θ(ξ = 0) = 1 θ(ξ = 1) = 0
where the objective is to find the continuous function θ(ξ) over the
domain of interest, viz. ξ ∈ [0, 1] for a prescribed set of parameters
{k, A, h, P , L}. All of these parameters can be constants, or some of them
might be dependent on the position ξ ( e.g., A(ξ)) or on the unknown
temperature itself ( e.g., k(θ)). We examine each case next.
For constant area, A and thermal conductivity, k, equation (7.1) re-
sults in a second order linear differential equation with constant coeffi-
cients for which an analytical solution is possible. But we focus only on
developing methodologies for obtaining a numerical solutions.
d2 θ hP L2
− θ = 0 (7.2)
dξ 2 kA
θ(ξ = 0) = 1, θ(ξ = 1) = 0
d2 θ dA(ξ) dθ hP L2
A(ξ) 2
+ − θ = 0 (7.3)
dξ dξ dξ k
dθ
θ(ξ = 0) = 1, = 0
dξ ξ=1
7.1. MODEL EQUATIONS AND BOUNDARY CONDITIONS 155
" #2
d2 θ dk(θ) dθ hP L2
k(θ) 2 + − θ = 0 (7.4)
dξ dθ dξ A
" #
dθ
θ(ξ = 0) = 1, k + hθ = 0
dξ ξ=1
Dθ = f on Ω
Bθ = g on ∂Ω
θ(ξ)
θ1
θ2
θi
∆ξ
ξ=0
ξ=1
1 2 i n
i=0 i=n+1
Figure 7.1: One dimensional finite difference grid of equally spaced data
points
θ̃0 in the first equation and θ̃5 in the last equation are known from the
Dirichlet boundary conditions. The above equations can be expressed in
matrix notation as, T θ̃ = b,
−(2 + α) 1 0 0 θ̃1 −θ̃0
1 −(2 + α) 1 0 θ̃2
= 0
0
0 1 −(2 + α) 1 θ̃
3
0 0 1 −(2 + α) θ̃4 −θ̃5
(7.5)
hP L2 2
where α = kA (∆ξ) . Note that the boundary values θ̃0 and θ̃5 appear
as forcing terms on the right hand side. Equation (7.5) is the discrete
version of equation (7.2). Once the structure is apparent, we can increase
n to reduce (∆ξ) and hence reduce the truncation error. In the limit of
∆ξ → 0 the solution to equations (7.5) will approach that of equation
(7.2). The matrix size will increase with decreasing ∆ξ and increasing n.
The matrix T is tridiagonal and hence the Thomas algorithm developed
in section §3.4.4 can be used to get the solution.
Once again the truncation error term has been retained at this stage, only
to emphasize that it should preferably be of the same order for every
derivative that has been replaced by a difference approximation; other-
wise the effective error is of the same order as the term with the lowest
order truncation error. Multiplying throughout by (∆ξ)2 and collecting
like terms together, we get,
" #
0 (∆ξ) hP L2 (∆ξ)2
A(ξi ) − A (ξi ) θ̃i−1 + −2A(ξi ) − θ̃i +
2 k
0 (∆ξ)
A(ξi ) + A (ξi ) θ̃i+1 = 0, i = 1, 2, · · · n + 1
2
Letting
0 (∆ξ)
ai = A(ξi ) − A (ξi )
" 2 #
hP L (∆ξ)2
2
di = −2A(ξi ) − i = 1, · · · n + 1
k
0 (∆ξ)
ci = A(ξi ) + A (ξi )
2
we can rewrite the equation as,
Observe that the coefficients {ai , di , ci } in the above equations are known.
However, unlike in equation (7.5), they vary with the grid point location
i. Also, for i = 1, θ̃0 on the left boundary is known through the Dirichlet
7.2. FINITE DIFFERENCE METHOD 159
which implies θ̃n+2 = θ̃n . This can be used to eliminate θ̃n+2 from the
last equation, which becomes,
Equation (7.6) is the discrete version of equation (7.3). Once the structure
is apparent, we can increase n to reduce (∆ξ) and hence reduce the
truncation error. In the limit of ∆ξ → 0 the solution to equations (7.6)
will approach that of equation (7.3). The matrix size will increase with
decreasing ∆ξ and increasing n. The matrix T is tridiagonal and hence
the Thomas algorithm developed in section §3.4.4 can be used to get the
solution.
x = xa + δ (7.8)
Neglecting second and higher order terms, one gets the linearized equa-
tion,
∂f
δ = −f (x a ) (7.10)
∂x xa
Similar concepts can be applied to a (system of) differential equations
as well. Consider for example the equation given below
" #
d dθ
k(θ)ξ =0 (7.11)
dξ dξ
" #2
d2 (θa + δ) d(θa + δ) dk
d(θ a + δ)
k(θa +δ)ξ +k(θa +δ) +ξ =0
dξ 2 dξ dθ θa +δ dξ
(7.14)
Note that each nonlinear term must now be expanded in Taylor series,
e.g.
dk
δ + ···
k(θa + δ) ≈ k(θa ) +
dθ θa
dk dk d 2k
+
≈ δ + ··· (7.15)
dθ θa +δ dθ θa dθ 2 θa
Now, terms of order δ2 and higher are neglected since δ is small. The
terms that are evaluated at the current guess θa are moved to the right
hand side. Hence we get,
d2 δ dk
d 2 θa dδ dk
δ dθa +
k(θa )ξ +ξ δ + k(θa ) +
dξ 2 dθ θa dξ 2 dξ dθ θa dξ
( )2 ( )
d2 k
dθa dk
dθa dδ
ξ δ + 2ξ
dθ 2 θa dξ dθ θa dξ dξ
)2
(
2
d θa dθa
dk dθa
= − k(θa )ξ + k(θa ) +ξ (7.17)
dξ 2 dξ dθ θa dξ
Note that the right hand side of equation (7.17) is the same as equation
(7.12) evaluated at θa and when it is zero the problem is solved! The
left hand side of equation (7.17) is linear in δ subject to homogeneous
boundary condition of δ(1) = 0 and δ(ξ0 ) = 0. Hence the solution (or
correction) δ(ξ) will be zero when the iteration is converged. Now one
can discretize equation (7.17) and solve for the correction iteratively.
Equation (7.17) can also be written in operator form as,
Dθ δ = −f (θ)
7.4. CONTROL VOLUME METHOD 163
θ(ξ)
θ1
θ2
θi
∆ξ
ξ=0
ξ=1
1 2 i n
i=0 i=n+1
where the linear operator Dθ , called the Fréchet derivative is given by,
" ( )#
d2 · dk
dθa d·
k(θa )ξ 2
+ k(θa ) + 2ξ +
dξ dθ θa dξ dξ
( )2
2k
dk d2 θa dk dθa d dθ
ξ + +ξ
a ·
dθ θa dξ 2 dθ θa dξ dθ 2 θa dξ
— LOUIS PASTEUR
Appendix A
Networked computing
environment within the
chemical and materials
engineering department
A.1 Introduction
AIX machines Nine IBM RS 6000 - model 220 in room CME 244 +
One IBM RS 6000 - model 550 as server
A.1
A.1. INTRODUCTION A.2
You are expected to be familiar with the basic concepts of operating sys-
tems, file systems, editors and structured programming and debugging
principles. I will focus on the concepts that are unique to the networked
environment and discuss briefly the software tools that are available for
various tasks. This document is intended merely as an introduction to
get you started and to identify the hardware and software resources that
are available on the network. Once you are aware of the art of the possi-
ble, you are on your own to make the proper choice of machine, software
tools and implement solutions strategies for solving a variety of prob-
lems. Advanced users should consult the original documentation on
each software. Online help is available for most of the software.
In a heterogeneous, networked environment, such as the one we have,
the range of services such as file space, printer, plotter capabilities, avail-
ability of specialized software etc. are distributed on a variety of ma-
chines, often matching the software needs with hardware capabilities.
For example, graphics packages and word processors on PC’s are ade-
quate for most document processing needs. Powerful editors are avail-
able on all of the machines; you may already have your own favorite
editor on one of these machines. Use it! Data processing, visualization,
and simulation of flow and chemical processes are numerically inten-
sive tasks and are best carried out on powerful workstations. MAPLE
(a symbolic computation package) and APSEN (a process simulator) are
made available only on one IBM RS 6000 machine for licensing reasons.
Hence it is essential to develop the skills to navigate through the network,
transfer data between computers and select the machine best suited for
a task.
Workstations using AIX or SUNOS operating system support multi-
tasking and multiple users. Multi-tasking implies that the computer can
handle several tasks (or processes) at the same time using time sharing
principles. In addition, AIX (and all other flavors of UNIX) can handle
A.1. INTRODUCTION A.3
Unlike DOS, UNIX is case sensitive and most of the UNIX commands are
in lower case.
A.1. INTRODUCTION A.4
X-windows
background screen.
Click the left Click the left When the cursor is in this
mouse button on a mouse button on a side region, clicking the left or
corner and drag to resize bar and drag to resize the right mouse button offers
the window window choice of additional
menus
A.2 Userid
All students get a userid on the General Purpose Unix servers (or GPU)
maintained by the Computing and Networking Services (CNS). If you also
purchase the Netsurf 97 CD-ROM from CNS (for about $10), you get a
powerful set of software for connecting your home computer to the IN-
TERNET through the University. For more information about computing
and network services see their Web site at http:\\www.ualberta.ca\CNS.
Once you get the userid on the machines gpu.srv.ualberta.ca you can en-
able access to the machines maintained by the department of chemical
and materials engineering by (a) signing on to gpu.srv.ualberta.ca and
(b) running the following script:
[userid@gpu]> /afs/ualberta.ca/labs/cmel244/bin/register-244
You need to do this only once at the begining of the year. If you
encounter any problems see one of the DACS center staff (Mr. Bob Barton
or Mr. Jack Gibeau).
Figure A.2 provides a conceptual frame work for introducing the net-
work structure. A variety of workstations and personal computers are
connected by ethernet. This local area network (LAN) is a subnet of the
larger university wide ethernet network as well as the world wide INTER-
NET network. The underlying communication protocol is called TCP/IP
(Transmission Control Protocol/Internet Protocol) and has been widely
accepted as the standard.
In addition to providing some basic connectivity between machines,
a network enables sharing of hardware and software resources as well
as sharing of information and communication on a world wide basis.
We will focus on the departmental subnet to illustrate various concepts
which can then be easily extended to national and international level
networks. The figure A.2 illustrates the logical dependencies for the
purpose of sharing resources between various machines and not the
physical connections. As a user, we need not concern ourselves with
the network hardware connections. It is sufficient to realize that any
machine on the network can address any other machine, much like tele-
phone connections. This immediately requires that each machine on
the INTERNET have a unique IP number and a host name. For exam-
A.3. OVERVIEW OF THE NETWORK A.6
U of A servers provide
HOME NEWS, ftp, Gopher, e-mail
services
te
s
X-server/clients
w
w t,
x- lne
x- lne
in ft
FORTRAN, emacs, gnuplot do p,
w
Room: CME 244 s
cmel31.ucs.ualberta.ca
to Room: CME 244
cmel39.ucs.ualberta.ca cmel11.ucs.ualberta.ca
IBM RS/6000 220 to
AIX 3.2.3 cmel28.ucs.ualberta.ca
NIS client to ugrads,
X-server/clients Prospec 486
OS/2
MATLAB, FORTRAN, emacs, X-clients
gnuplot, xmgr, khoros, tex
DOS/Windows emulation,
Lotus 123, Wordperfect
AIX 3.2.3
te
X-server/clients
w t,
x- lne
ple the server within the department of chemical and materials engi-
neering for undergraduate student use has the IP number 129.128.44.50
and the host name ugrads.labs.ualberta.ca. The part of the IP number
"129.128.56." represents the department of chemical and materials engi-
neering subnet and we can connect up to 256 computers to this subnet.
Similarly the last part of the host name, viz. eche.ualberta.ca, also called
domain name represents the chemical and materials engineering do-
main. Different machines on this domain will have different names like,
prancer.eche.ualberta.ca, ravana.eche.ualberta.ca. Table A.1 lists com-
puters that are generally available for chemical and materials engineer-
ing students and staff. To determine your eligibility to have access to
any of these resources see one of the DACS center staff. Typically under-
graduate students can expect to have access to ugrads.eche.ualberta.ca
and the associated machines, while graduate students and staff will have
A.4. THE CLIENT-SERVER MODEL A.8
ethernet
chopin.eche.ualberta.ca
ravana prancer comet
NFS clients
/usr/local
The file system chopin:/usr/local
NFS SERVER is mounted as /usr/local on each of
these machines. Logically it appears as a local
The file system /usr/local file system. But any directories and files under
resides physically in chopin /usr/local are actually fetched from chopin.
but has been exported to a group
of machines
tion and served by the NIS (Network Information Service) server machine.
Figure A.4 shows a such a setup.
The University of Alberta supports sharing of the same file space from a
variety of machines on campus. There is a single home directory for
each userid from any UNIX machine on campus. CNS provides lim-
ited amount of disk space for each user (about 10Meg). In addition
the department of chemical and materials engineering provides addi-
tional space to undergraduate students under a directory called lab-
disk and for graduate students under a directory called chemeng. The
relevant directories will be found as a subdirectory under the home
directory of each user. To learn more about AFS go to the web site
http://www.ualberta.ca/HELP/afs/afs1.html.
ethernet
ravana.eche.ualberta.ca
jhm2 dina comet
NIS SERVER
serves information on NIS clients
/home user ids and passwords When you attempt to signon to a client, it verifies
to other clients. with the NIS server that your user id is a valid one.
Your home directory is also made available on each client.
The file system /home
contains home directories of users.
It has been exported to other machines.
A.4.3 X servers
X-windows is a sophisticated communication/window management soft-
ware developed at MIT. It uses TCP/IP for communication. It allows you
to interact with the local workstation through windows, menus, dialog
boxes, icons etc., in an intuitive way and minimizes the need for interac-
tion through command lines. One can view this as the next logical step
in the historical progression of the way humans have interacted with
computers. Originally it was accomplished through batch processing,
followed by interactive computing using commands which is being re-
placed currently by more intuitive interaction through a Graphical User
Interface (GUI) using menus and icons. One can expect this to be fol-
lowed by voice level interaction, leading ultimately to interaction with
A.4. THE CLIENT-SERVER MODEL A.12
ethernet
Command sequence What they do
1. login signon to the local machine with user id and password
2. xinit start the X-server
3. xhost remote permit remote machine to send display to local
4. rlogin remote signon to the remote machine from local
5. aixterm -display local:0 & start X-client on remote and redirect the display to local.
NOTE: Substitute the actual name of the machine for local and remote. Use fully qualified
domain names if the machines are on different subnet.
user@machine:dir> tin
This program maintains a local database of the news groups that you
have subscribed. It fetches the latest articles from the server and allows
you to read and, optionally respond to articles. If you post a response,
it goes to the whole internet community. This service is a privilege and
should be used responsibly. Any abuse of the system will result in denial
of access to the entire network services.
While the News service allows two-way communication and thus active
participation, Gopher is a worldwide one-way information retrieval ser-
vice. A number of Universities and organizations participate in provid-
ing this service. The University of Alberta is one of the participants. The
Gopher server is maintained by Computing and Network Services on one
of their workstations. Any client on the campus ethernet (or even from
a home computer with a modem) can connect to this server and browse
through a wealth of information on such topics as
1. What is CWIS?/
2. What’s New on CWIS?/
3. Student Information and Services/
4. Libraries on the Network/
5. University Faculties and Departments/
6. Administrative Policies and Procedures (MAPPS)/
7. Campus Phone Directory <CSO>
8. Computing Resources/
9. International CWIS Systems/
10. Magazines and Publications/
11. University Services Directory/
12. Weather Report.
user@machine:dir> gopher
When you are logged on to gpu.srv.ualberta.ca, you can also access go-
pher or world wide web by entering
user@machine:dir> lynx
This is a high end version of information sharing tool (like gopher) us-
ing windows and hypertext links established between computers on the
internet on a global level. It also operates on a client-server model.
Netscape is available on all of the AIX machines. Anyone with some
information to share can operate a server on one of their workstations
and there are thousands of such servers on the INTERNET. To access
information on WWW, start the client on your local workstation by en-
tering the following after you have started X-windows.
user@machine:dir> netscape
Your client should automatically know where the nearest server is lo-
cated. Typically there will be home page from where you can begin your
exploration. Have fun! Watch the time you spend on this one!! It is a
time sink!!!
A.5 Communication
for VT100 emulation ( i.e., full screen use of editors like emacs,
news reader tin, e-mail program pine and gopher) and tek-
tronix emulation ( i.e., plotting programs like gnuplot can dis-
play graphs on your home computer in color!) and file trans-
fer between home computer and the university computer. You
can get a copy of MS-KERMIT Ver 3.10 for your PC from DACS
center staff. It can be distributed freely without any licensing
problems. Additional details can be found in Gianone (1991).
ftp Preferred for file transfer over ethernet. Both AIX and OS/2
provide support for ftp.
Remember that you can choose any one of the 9 AIX machines in
the network. You will see the same home directory and other soft-
ware resources from each of the nine machines. Hence choose a
random number between 31 and 39, so that no one machine is over
loaded all the time.
login: userid
Password: password
• Start the aixterm client on the remote machine, redirecting the dis-
play to the local machine by entering
user@machine:dir> open-Xpc nn
• After some delay, an AIX window will open on your local 486 sta-
tion! Now you are connected to the AIX machine and typically you
will be in a shell called “ksh”. You can start any application like
MATLAB, xmgr etc. by simply entering the name of the program
e.g.,
A.5. COMMUNICATION A.19
user@machine:dir> matlab
user@machine:dir> mmg
• Before you leave the OS/2 station, either logout from the remote
machine with the logout command as follows
MS-KERMIT>
At this stage you can ask for additional help on kermit by entering the
kermit command help or ?. But the connection to the University network
must be done manually with the following commands
A.5. COMMUNICATION A.20
DIAL>
telnet, 129.128.44.50
or
telnet, ugrads.eche.ualberta.ca
to get connected to the AIX machine or any other valid internet number
(or name) for which you have a valid userid.
All the PCs in room CME 473 and those in staff offices that have ethernet
cards are connected to INTERNET. The communication program tn3270
is also available in each of the machine. On these machines you can start
the connection by entering,
user@machine:dir> kermit
C-Kermit>
Enter,
MS-Kermit>
Any command you enter now is acted up on by the local PC. To fetch a
file from the AIX machine (in your home directory, of course) to local PC,
enter,
The file transfer program called ftp allows transfer of files between ma-
chines on ethernet. This is also implemented on the client-server model.
From a local machine connect to the remote machine as follows:
On the remote machine the ftp daemon called ftpd acts as the server.
You will be prompted for userid and password. Once the connection is
established you can use the commands shown in Table A.3 to transfer
file.
The FTP procedure summarized above is essentially the same on
most of the machines. Be bold and try them out and observe how fast
the file transfer is compared to KERMIT through a serial line.
A.6. OPERATING SYSTEMS A.23
• Make sure that you have a writable, formatted floppy disk in drive
A: of an OS/2 machine.
• Enter,
[C:\] lcd A:
Login procedure
Logout procedure
Once you login successfully to an AIX machine, you will always start the
session in your home directory. There should be a file in your home
directory named .profile. Every time you login, the contents of this file
are executed once. Hence one can use this file to customize the work-
ing environment on an AIX machine with the help of this file. There is
also a system wide profile file, which is used to control such things as
the default search path for finding executable programs, controlling the
prompt string, identifying the terminal type, and to define a number of
environment variables that other application programs might need.
You can feel free to copy my version of this file in /u/kumar/.profile
and adopt it to your needs. My version of this file enables the command
line editing features - i.e., all the commands that you enter during a ses-
sion are stored in a buffer and you can scroll back and forth to retrieve
previous commands with Ctrl-p for previous and Ctrl-n for next. After
retrieving a previous command you can edit it with the cursor movement
keys Ctrl-b for backward, Ctrl-f forward and Ctrl-d for deleting the cur-
rent character. In effect it supports the same editing capabilities on the
command line that the editor emacs supports for a file. More on emacs
later. You can also set alias for the most frequently used commands.
For example you can set
alias dir=’ls -al’
so that when you enter dir you will get the directory listing. Another
useful alias is
alias rm=’rm -i’
which prompts you for confirmation before removing (deleting) files.
If you are familiar with the DOS directory and file structure, it should be
equally easy to work with the file systems of OS/2 and AIX. While DOS file
A.6. OPERATING SYSTEMS A.25
names are restricted to 12 characters, AIX allows very long file names.
But the mechanisms for creating directories and navigating up and down
the directory tree structure are essentially the same. Frequently used
commands that relate to file management are tabulated below.
These are called manual pages or man pages for short. Try
to get started! Although the man pages provide only limited help, they
are always available from any type of terminal. Much more exhaustive
online help using hypertext is available when you are connected to an
AIX machine via X-windows. To access this enter
user@machine:dir> info
A.7 Editors
The functions that one expects from a good editor have several common
features. These can be broadly grouped into the following.
user@machine:dir> emacs
The anatomy of the emacs editor screen is shown in Figure A.6. This
is also a full screen, visual editor. It works under both X-windows and
VT100 emulation.
Buffers
Emacs uses the concept of a buffer to keep a temporary copy of the file
that you are editing. You can edit any number of files at a time and each
A.7. EDITORS A.27
%%
C-p
file is kept in a separate buffer. There is a one line command buffer called
minibuffer at the bottom of the screen and a text buffer at the top. A
status line in reverse video separates the minibuffer from the text buffer.
The key sequence C-x b allows you to cycle through the buffers.
Key sequences
Being the most powerful editor, emacs provides a large number of edit-
ing functions. These functions are accessed either by entering the func-
tion name in the command minibuffer or by directly entering a key se-
quence. This process of attaching key sequences to functions is called
key bindings. Actually when you enter a key sequence like C-f, it invokes
a function called forward-char. Some of the frequently used functions
and their key bindings are listed in Table A.7.1. In these C-x means the
keeping the control key pressed, enter the character x, while M-x implies
a two-character key sequence with the Esc key as the first one followed
by the character x. If you get into trouble or become confused with this
editor at any time enter the key sequence C-g C-g to discontinue what
you started. This means that while keeping the control key down, enter
the letter g couple of times.
Command completion
NOTE: C-h means keeping the control key down, enter the key “h”.
M-v means press and release the Meta key or the Esc key, then press the
key “v”.
C-x [ means keeping the control key down, enter the key “x”, then press
the key “[”
Table A.4: List of frequently used emacs functions and their key bindings
A.8. FORTRAN COMPILERS A.30
Emacs contains many more functions than listed in Table A.7.1 and
not all functions have key bindings. You are encouraged to go through
the online tutorial which can be invoked with the keystrokes C-h t. Online
documentation is available via C-h C-h i. The key sequence C-h C-h b
will show all the key bindings within emacs in a buffer called *Help*
after splitting the screen into two windows. You can switch to the lower
window with the key sequence C-x o which is the same as invoking the
function other-window. Repeating the key sequence C-x o will cycle you
through the various windows. To expand the current buffer into full
screen use the key sequence C-x 1.
This is only a minimal introduction to emacs. This editor is not for
the uninitiated user. You need patience to master this editor, but if you
persist the rewards in terms of increased productivity are great. With
this introduction you should be able to explore emacs deeper and deeper!
If you are bored while using emacs, chat with the doctor - use M-x doctor
- have fun.
This is adequate for any self contained FORTRAN program. The -O op-
tion invokes optimization of the code. The executable code from the
compiler will automatically be stored in a file named a.out. To execute
your program use,
user@machine:dir> a.out
If you read data from unit 5 and write data to unit 6 within your FOR-
TRAN program, these I/O will be redirected, by default, to your terminal.
If you want to use files connected to these units, then you can use
Another way to use these files is to OPEN then explicitly within your
FORTRAN program.
If your program calls any library routines like the nswc math library,
then you must specify the location of the library as follows in the com-
A.9. DEBUGGERS A.31
pilation step.
Here -l parameter identifies the name of the file containing the library
and the -L parameter identifies the directory where the library file re-
sides. Note that the library file will be named libnswc.a. By convention,
however, the prefix lib and the postfix .a need not be specified in the
parameter -l.
Use the man xlf to find about other parameters the xlf compiler can
accept.
A.9 Debuggers
A source level debugger allows one to step through the program, exe-
cuting one line at a time, set break points at pre-selected lines, display
values of variables and change values of variables. There is an excellent
X-Windows based front end called xde to the debugger (dbx) on the RISC
server that is quite easy to use. Find out more about it using man xde. If
you want to use this debugger, however, you should access the computer
through X-Windows.
In order to enable the debugging features you should compile the
program with the -g option as follows.
The a.out file so produced will contain all the symbol table information
which is needed by the debugger. To invoke the debugger use,
This will open up several windows, one of which will show the source
listing. Other windows provide menus and buttons that you can use
to set break points, begin execution, display variables etc. There is also
online help explaining the various features of xde.
For the real computer hacks, a command line version of the debugger
called dbx is available. You can use this to debug FORTRAN, C and
PASCAL programs. Venturing into this is recommended only if you know
the language C quite well. This can be accessed, however, without X-
windows.
A.10. APPLICATION PROGRAMS A.32
user@machine:dir> mmg
user@machine:dir> aspen
The input file containing the commands to ASPEN PLUS must be pre-
pared by the user using any standard editor. One can think of the Model
Manager as a front end that enables you to build the command file for
ASPEN PLUS in a GUI environment.
A.10.2 Xmgr
This is a powerful 2-D plotting and data analysis package. You can con-
trol every facet of the graph with this program. It runs only under X-
A.10. APPLICATION PROGRAMS A.33
user@machine:dir> xmgr
A.10.3 TEX
TEX is a powerful typesetting package that is widely available on several
platforms and it has very few licensing restrictions. This document, in
fact, was typeset using TEX. It is available on most of the AIX machines.
The authoritative document on TEX is by Knuth (Knuth, 1984) and on
LATEX is by Lamport (Lamport, 1986). The steps for compiling, previewing
and printing a TEX document are outlined here. See the above references
on how to create a TEX document. To compile a TEX file use,
Note that on the AIX machine, you must be using X-windows to use the
previewer. A program called dvips takes the "dvi" file and sends it to
a postscript printer. Since printer configurations vary, see one of the
support staff to find out the exact procedure for printing a document.
user@machine:dir> pine
This program will work under VT100 emulation and offer full screen
support. Online help can be accessed with the question mark, ?. Note
that e-mail addresses are formed as userid@machine.eche.ualberta.ca.
Here userid is your signon name or id on the AIX machine, machine is the
name of the machine. The rest of the e-mail address, eche.ualberta.ca
refers to the chemical and materials engineering subnet domain name.
If you have accounts on several machines it is recommended that you
select and consistently use one machine as your primary e-mail system.
Tin is the standard news reader on our AIX network. To start it simply
enter
user@machine:dir> tin
This program will work under VT100 emulation. Online help can be
accessed with the "h" key.
For the experts, online documentation via man pages is available on each
of the above commands. The following examples illustrate how to con-
struct a script file that you would submit using qsub.
A.11. DISTRIBUTED QUEUEING SYSTEM A.35
#!/bin/csh
# make the current directory the CWD
#$ -cwd
# lets put STDOUT/STDERR in the file "gaga"
#$ -eo gaga
# i’d like to know when she fires
#$ -mu user@address.ualberta.ca
#$ -mb
# and when she finishes
#$ -me
matlab >out « ’eof’ #the shell starts matlab; output goes to "out"
secant(’ass3a’,[0,1],eps,1) %matlab acts on this line and runs secant
fzero(’ass3a’,0.5,eps,1) %matlab acts on this line and runs fzero
quit %matlab acts on this line and quits
eof
ps -ael #back in the shell; output goes to "gaga"
ls -al #The shell acts on this too!
In the above file any line beginning with "#$" is a command for the
queueing system and any line that begins with "#" is a comment line.
The command
#$ -eo gaga
send all of the output that normally appears on the screen during an in-
teractive session to a file named "gaga". [Change the file name to some-
thing different from "gaga"!] The command
#$ -mu user@address.ualberta.ca
sends mail to the user when the job starts. Use your correct e-mail ad-
dress here. Similarly the command
#$ -me
sends mail when the job finishes.
After the preamble you can put any sequence of commands that you
would normally enter during an interactive session and these will be ex-
ecuted in sequential order. In the above example the command
matlab >out « ’eof’
starts MATLAB, redirects MATLAB output to a file named out and takes
the input to MATLAB from the following lines until "eof", the end-of-file
marker. The lines following "eof" should make sense to the shell, as it
interprets these lines. If you understand these principles you can con-
struct any complicated script using the full programming capabilities of
A.12. PRINTING REPORTS, GRAPHS ETC. A.36
The machines are grouped into "High", "Medium" and "Low" groups based
on the hardware capabilities. Here "-G" identifies the group as "Medium"
and only one machine is requested for the job with "1". Note that DQS
supports "parallel virtual machine" for jobs that can be executed in par-
allel on more than a single machine. In such cases you should request
the number of machines by replacing "1" with "n" where "n" can be be-
tween 1 and 9 since we have only nine machines. The default group is
"Medium" and the default number of machines is "1". So you could have
simply entered,
user@machine:dir> qstat
#!/bin/csh
#$ -cwd
#$ -eo gaga
#$ -mu user@address.ualberta.ca
#$ -mb
#$ -me
runf3d -fort m02.f -command m02.fc -release 3.2.1 -geom m01.geo
In room CME 244 there are several old Epson printers connected directly
to the OS/2 machines. Each printer serves two OS/2 machines. In room
CME 473 each of the DOS machine is connected directly to a HP Laser Jet
printer.
Since AIX and OS/2 have network support, printing on these ma-
chines can be done using network printers. Hence there are no printers
connected directly to each of these machines. There are two network
A.12. PRINTING REPORTS, GRAPHS ETC. A.37
LaserJet printers, one located in room CME 244 and the other in CME
473. The network printers also operate on the client-server model. It
is important that you understand how the print servers operate and
use this facility in a responsible manner. If the facility is abused this
service will be discontinued and you will have to take your print jobs to
the Micro DEMO center at the book store!
• If you send a print job to a remote location, the job can be deleted
by the system administrator if it interferes with other queued print
jobs.
Most applications running under OS/2, AIX or DOS can generate printed
output for a number of different types of printers. Each type of printer/plotter
understands a particular set of instructions. For example HP LaserJet
uses PCL (Print Control Language) format, while HP plotters use HPGL
(HP Graphics Language). Another widely used page description language
is called Postscript. Application programs use something called a printer
driver to generate the output suitable for a particular output device.
If the output is generated on a computer that is connected directly
to a printer (like most DOS machines to HP LaserJet in CME 473 or OS/2
machines to Epson in CME 244) then you can send the print job directly
to the printer, typically through the printer port LPT1:
If the output is generated on a computer that does not have a printer
connected directly to it or you want a LaerJet output from an OS/2 ma-
chine, then you must use one of the network printers. In this case you
must first save the output from the application program into a file. Most
well designed application programs will give you the option to select the
output device and to save the printed output into a file. Use the follow-
ing convention in naming the output files:
A.12. PRINTING REPORTS, GRAPHS ETC. A.38
filename.ps postscript
filename.eps Encapsulated postscript
(Useful for merging graphics with text)
filename.pcl HP Laser Jet
filename.hgl HP plotters using HPGL instruction set
filename.dot Epson dot matrix printers
Note that such files contain specific instructions that are understood by
specific printers/plotters. Hence they must be sent to the appropriate
printers. If you send a PCL file to an Epson printer you will get garbled
output that will make no sense!
Unix experts may want to try the basic set of unix commands lpr, lpq,
lprm to submit, monitor and manage a print task. On the AIX machines,
the command to submit a PCL file to a network printer is
where the printer name is either LJ 244 (LaerJet printer in room CME
244), LJ 473 (LaserJet printer in room CME 473) or PS 475 (the postscript
printer in room CME 475). Your job is then queued and you can examine Note that PS 475 is
the status of the queue with the command, available only on
the graduate
user@machine:dir> lpq -Pprinter name network, while
LJ 244 and LJ 473
are available on the
You can remove your print jobs from the queue with the command,
undergraduate
network.
user@machine:dir> lprm -Pprinter name job number
If you are using X-windows and want to preview the contents of the file
fname.ps enter,
user@machine:dir> DISPLAY=hostname:0
user@machine:dir> gs fname.ps
where hostname is the name of the X-client. To find out more about
"ghostscript" options use one of
user@machine:dir> gs -?
user@machine:dir> man gs
Important Note: Once you have printed the document delete the output
files from your home directory.
as the password. Recall from section §A.10.4, that the e-mail addresses
have the general form userid@machine.eche.ualberta.ca. You must be
courteous in using such services. Normally you are requested to down-
load software only during off-peak hours. You must also conform to all
the software licensing conditions. A sample ftp session is given below.
Appendix B
An introduction to MATLAB
B.1 Introduction
B.1
B.2. STARTING A MATLAB SESSION B.2
For the adventurous, here are some of its advanced features. Explore
them on your own! The package provides features (or tool boxes) for sig-
nal processing, control system design, identification and optimization
through what are called m-files. The graphic features support include
3D and contour plotting as well as device drivers for a variety of out-
put devices including Postscript and meta file capabilities for producing
high quality plots (not just screen dumps!). It also provides facilities
for developing ones own tool boxes as well as facilities for interfacing
with other high level languages such as FORTRAN or C and invoke such
routines from within MATLAB.
user@machine:dir> xinit
You may copy the files ".mwmrc" and ".Xdefaults" from the directory
"/afs/ualberta.ca/home/k/u/kumar/". These files customize the X-windows
environment when the X-server is started with the command "xinit". Sev-
eral windows will be started up and one of them will be named "Aixterm".
Normally this would be the shell "ksh" and all the paths to application
program will be setup correctly for you to start running application pro-
grams. To start MATLAB simply enter
user@machine:dir> matlab
If MATLAB does not start, seek help from the system administrator!
user@machine:dir> matlab
Once you start MATLAB successfully, you should see the following prompt
on your screen.
< M A T L A B (tm) >
(c) Copyright 1984-92 The MathWorks, Inc.
All Rights Reserved
Version 4.0a
Dec 11 1992
»
This provides you with an interactive workspace in which you can define
any number of variables and invoke any function. To exit MATLAB at
any time enter
» quit
The commands that you enter within MATLAB are acted upon immedi-
ately. As soon as you enter a line like,
» fname
» !ls -al
MATLAB provides extensive online help using commands like help, demo,
type, lookfor, whatsnew. They are not only useful for checking the syn-
tax of a particular function, but also for exploring and learning about new
topics. Since the help command often generates lots of text that tend to
scroll by very quickly, it is useful to enable a feature called “more” with
the command,
» more on
When this is enabled, you will be shown one screen full of information
at a time. Note that this is also UNIX feature that you can use with any
program that generates lots of scrolling text. To get started with the
online help, first get a list of help topics using
» help
Table B.1 provides a list of help topics which should give you some idea
about the broad scope of MATLAB. You can obtain a list of functions
under each topic (or directory) by entering help topic. For example to
get a listing of general purpose commands (the first item in the above
table) enter,
» help general
» lookfor inverse
which will scan for and print out the names of functions which have the
keyword "inverse" in their help information. The result is reproduced
below.
• MATLAB remembers the previous command lines that you have en-
tered. You can recall them by simply using the up and down arrow
keys (or ctrl-p and ctrl-n key combinations) and then edit them
and reenter the edited command as a new command. Basically,
it supports the following emacs key definitions for command line
editing.
B.3. MATLAB BASICS B.9
» A = [1 2 3; 4 5 6; 7 8 9]
» x=[2+4*i, 3+5*i]
» A(2:3,1:2)
Observe the use of () and : to select a sub block of A. Next, try What might
happen if the size
of sub-blocks are
different?
B.3. MATLAB BASICS B.10
» B(4:5,2:3)=A(2:3,1:2)
» global A
» isglobal(A)
» whos
B.3. MATLAB BASICS B.11
» x = 0 : 0.05 : 1.0
will generate x = [0 0.05 0.1 0.15 0.2 · · · 1.0]. (Try help colon).
• To suppress the automatic echoing of any line that you enter from
keyboard, terminate such a line with a semi-colon ";". For example
» x = 0 : 0.05 : 1.0;
will define x as before, but will not echo its value. (Try help punct).
• To continue the entry of a long statement onto the next line use an
ellipsis consisting of three or more dots at the end of a line to be
continued. For example
» format long
• You can save the contents of a workspace with the "save" command.
Try, Try the command
!ls jnk*
» save jnk Observe that the
extension .mat has
In the next few statements examine the currently defined variables, been added
clear the workspace and load a previously saved workspace.
» whos
» clear
B.3. MATLAB BASICS B.12
» whos
» load jnk
» whos
== equal
˜= not equal
» x = A\b
» A*x - b
B.3. MATLAB BASICS B.14
» norm(A*x - b)
» rank(A)
» det(A)
» det(L)*det(U)
» [v,d]=eig(A)
» prod(diag(d)) Can you explain
this result?
» c1=poly(A)
» roots(c1) Can you explain
» prod(ans) these results?
The other functions of possible interest are fmin, fmins, residue, conv
, table1.
In this exercise you produced the data from within MATLAB. If you have
columns of data in a file, you can read them into MATLAB and plot them
as above. The postscript file produced in the above example can be
merged with other documents or printed on a postscript printer. Use
help print to find out about support for other type of printers and plot-
ters.
Example
1
G=
(s + 1)(s + 2)(s + 3)
» num = 1;
» den1 = [1 1];
» den2 = [1 2];
B.3. MATLAB BASICS B.20
» den3 = [1 3];
» den = conv(den1,conv(den2,den3));
» loglog(w,mag)
» semilogx(w,phase)
Y G c Gp
=
Ysp 1 + G c Gp
» [A,B,C,D] = tf2ss(num,den);
dx
where A, B, C, D are matrices in the differential equations dt := Ax + Bu
and y = Cx + Du. To obtain a discretized model, the function c2d is
used:
» y = dstep(ad,bd,C,D,1,100);
» plot(y),title(’step response’);
» diary file
will start recording every keyboard entry and most of the computers tex-
tual response (not graphics) in file. To suspend the recording, use
» diary off
» diary on
The file contains simple text (ASCII) and can be printed on the network
printer.
B.3. MATLAB BASICS B.22
» path
You can list the contents of a m-file with the type command. While the
help command produces only documentation on the function, the type
command produces a complete listing of the function. Try,
» type sin
» help sin
» type erf
» help erf
Note the “sin” is a built-in function and hence no code is listed. On the
other hand “erf” is the error function implemented as a m-file and hence
a complete listing is produced.
The m-files can take two forms - viz. (i) a script file and (ii) files that
define entirely new functions. Such files should be in the MATLAB search
path.
In a script file, you can put any MATLAB commands that you would
normally enter in an interactive session. Simply entering the name of
the file would then execute the contents of that file. For example to
enter a large matrix, create a file called "A.m" in your home directory
using your favorite editor. This file should contain the following text.
B = [ 1 2 3 4 5 6 7 8 9;
2 3 4 5 6 7 8 9 0;
3 4 5 6 7 8 9 0 1;
4 5 6 7 8 9 0 1 2;
5 6 7 8 9 0 1 2 3]
b=sin(B)
B.3. MATLAB BASICS B.24
»A
Note that a matrix variable "B" of size (5 × 9) has been defined in your
workspace and the variable "b" contains the values of sin(B).
In a script file you can include any such sequence of valid MATLAB
commands, including program flow control commands like for, if,
while loops etc. However a script file is not a function file and hence
you cannot pass any arguments to the script. Also, when you execute
a script file from the workspace, all of the variables defined in a script
file become global variables. In contrast any variable defined within a
function file is local to that function and only the results returned by the
function become global in nature.
function f=flash(psi)
% Calculates the flash equation f=flash(psi,K,z)
% K is a vector of any length of equilibrium ratios
% z is the feed composition (same length as K)
% K, z are known.
% psi is the vapor fraction
% This is the last line of help. Notice the blank line below!
global K z
f=((1-K).*z) ./ (1+(K-1)*psi);
f=sum(f);
Let us understand the anatomy of this function. The first line should
always contain the keyword "function" in order to identify it as a func-
B.3. MATLAB BASICS B.25
tion definition and not a script file. Then a list of values computed and
returned by the function should appear - in the present case only "f" is
being returned. If you have more variables being returned you would
list them as "[f1, f2, f3] etc. Next, the equal sign is followed by the
name of the function. Then the list of input variables are given in paren- Note that the file
thesis. The next several lines begin with the percent sign (%) and hence name is
are treated as comments. Here is the place to put the documentation constructed by
appending ".m" to
on what the function does and how to use it. This is also the part that
the function name.
is printed out when a user asks for help on this function. A blank line
In the above
signifies the end of the help message. The actual code follows the blank example the file
line. Notice the use of element-by-element multiplication of two vectors name will be
which avoids the use of do loops. How elegant! flash.m
Assuming that you have created a file called "flash.m" containing
the above lines, work through the following steps.
» help flash
» type flash
» global K z
» z=[.25 .25 .25 .25]
» K=[1 .5 .4 .1]
» whos
» flash(0.1)
If you know any one high level programming language such a FORTRAN,
C or even BASIC, you should have no difficulty in understanding the ele-
mentary program flow control features of MATLAB. A list of help topics
is given in Table B.6. Let us take the example of "flash.m" and illustrate
the use of "if" and "for" constructs. First we check if the length of vec-
tors K, z are the same; if not we generate an error message. Note the
length and error are built-in MATLAB functions. In the next section
we determine the length of input vector "x" and build a loop to calculate
the function for each element of "x" and store it in the corresponding
element of "f". Use "help relop" and "help lang" to find out more about
relational operators and programming language features.
B.3. MATLAB BASICS B.26
Example
function f=flash(x)
% K is a vector of any length of equil ratios.
% z is the feed composition (same length as K)
% K, z are defined as global in main
% x is the vapor fraction
% The following is the isothermal flash eqn.
global K z
if ( length(K) ˜= length(z) )
error(’Number of K values & compositions do not match’)
end
Since all the variables with in a function are treated as local variables,
their values are not available in the workspace. To examine their values
within a function, you have to be able to stop the execution at a spec-
ified line within a function and examine the values of local variables.
The following exercise illustrates the debugging process using the flash
function developed earlier. So we assume that a "flash.m" file exists in
your current directory.
— IZAAK WALTON
So is UNIX.
— K. Nandakumar
Appendix C
user@machine:dir> chsh
This command will display your current shell, and prompt you for the
C.1
C.1. INTRODUCTION TO THE SHELL AND THE DESKTOP C.2
name of the new shell. The change takes effect when you login the next
time. At any time you can invoke a new shell, different from the login
shell, e.g.,
user@machine:dir> csh
invokes a C-shell.
You can invoke a desktop at any time on AIX machines by entering
user@machine:dir> xdt3
Since the use of desktop is supposed to be rather intuitive, you are en-
couraged to explore its features on your own!
PATH=$PATH:$HOME/bin:$KHOROS_HOME/bin
HOSTNAME=‘hostname‘
PS1=’ $LOGNAME@$HOSTNAME:$PWD>’
EDITOR=emacs
user@machine:dir> alias
By default, the "rm" command removes files without prompting you for
confirmation which could result in accidental deletion of files. The alias
defined above, assigns ’rm -i’ to "rm". The keyword "-i" stands for inter-
active mode and hence you will always be prompted before removing a
file.
The variables defined in a shell environment are available only to that
shell environment and not to other shells that you may start from the
current one. The export command is used to export the variables to all
subsequent shells. The last line in the above example exports several
environment variables.
To look at all of the environment variables defined in the current ksh
shell, enter,
user@machine:dir> set
user@machine:dir> DUMMY=junk
C.2. MANAGING FILES C.4
In managing your files and directories, you need to be able to list the
contents of a directory or file, copy and move files, compress and uncom-
press files, create and delete files and directories, control the ownership
and access to files etc. Commands to carryout these tasks are illustrated
below with specific examples. Try them out at a terminal. To get a com-
plete description of each command use the man pages i.e.,
user@machine:dir> man command
The ls command produces a listing of all the files in the current direc-
tory. In its most useful form, you will use the “-al” keywords, i.e.,
Typically, files that begin with the “.” ( e.g., .profile) are treated as hidden
files. They keyword “-a” however lists all of the files including the hid-
den ones. The keyword “-l” produces the long listing, a sample of which
is shown in figure C.1. This listing provides information on file access
control, ownership, size, time stamp etc. Each line contains information
for a file or directory. The first character identifies whether it is a file (-),
a directory (d) or a symbolic link (l). A symbolic link is a pointer to some
other file (think of it as an alias). The next set of nine characters iden-
tify the file access control, in groups of three. Since AIX is a multiuser
environment, users can control ownership and access of their files to
others. The possible access modes are: read (r), write (w) execute (x) or
none(-). These modes apply to (user, group, others). The groups are es-
tablished by the system administrator. The owner and group names are
listed next, followed by file size in bytes, the time stamp for last change
and the file name.
C.2. MANAGING FILES C.5
permission
time stamp File name
{
{
control Owner Group File size
{
{
{
{
drwxr-sr-x 27 kumar sys 1536 May 24 23:14 .
drwxr-sr-x 59 sys sys 1536 May 13 08:52 ..
-rw-r--r-- 1 kumar others 1937 Jan 07 11:47 .Xdefaults
drwx------ 2 kumar others 512 Jul 21 1992 .elm
-rw-r--r-- 1 kumar sys 2504 May 19 12:08 .mwmrc
-rwxr-xr-x 1 kumar sys 610 May 04 12:36 .profile
-rw------- 1 kumar sys 348 May 14 12:22 .rhosts
drwxr-xr-x 3 kumar others 512 Jul 21 1992 .tin
-rw-r--r-- 1 kumar sys 136 May 11 14:11 .xdt3
-rw-r----- 1 kumar others 1222 Jan 19 1992 Ass1.m
drwxr-xr-x 2 kumar others 512 May 19 13:12 CHEM2
drwx------ 2 kumar others 512 May 27 1992 Mail
{
r read permission
w write permission 1st set applies to owner
x execute permission 2nd set applies to group
- no permission 3rd set applies to all
d indicates a directory
l indicates a symbolic link
Examples:
The file .profile has (read,write,execute) permission for owner (kumar in this case) and
(read,execute) permission for both the group (sys in this case) and everyone.
The command
chmod g+r file
will give read access to group for file, while
chmod o-w file
takes away write access to all for file
Other related Unix commands
ls -al - detailed listing of directory such as the above
chmod - change permission on files and directories
chown - change ownership of files and directories
rm - remove or delete a file
rmdir - remove or delete a directory
mkdir - create a new directory
The chmod command allows you to modify the access control of files and
directories.
Examples
Note the the "-R" flag stands for recursive use of the command for
all files in all subdirectories.
The mv (move) command moves files and directories from one directory
to another, or renames a file or directory. You cannot move a file onto
itself.
Warning: The mv command can overwrite many existing files unless you
specify the -i flag. The -i flag prompts you to confirm before it overwrites
a file.
Examples
This moves all files and directories under olddir to the directory
named newdir, if newdir exists. Otherwise, the directory olddir is
renamed to newdir.
Examples
If file.new does not already exist, then the cp command creates it.
If it does exist, then the cp command replaces it with a copy of the
file.old file.
Also try the GNU version of compress utility called gzip and gunzip -
they are more efficient in both speed and size.
Examples
user@machine:dir> rm myfile
If there is another link to this file, then the file remains under that
name, but the name myfile is removed. If myfile is the only link,
the file itself is deleted. Caution: You are not asked for confir-
mation before deleting the file. It is useful to set an alias in your
".profile" file to redefine "rm" as
After each file name is displayed, enter "y" to delete the file, or
press the Enter key to keep it.
user@machine:dir> ps -ael
This provides a long listing of all the currently running processes in-
cluding all of the daemons started by the root at the time of booting the
computer. A typical sample output might look like,
The process name (or the command name) is shown in the last col-
umn. Other useful parameters are the process identification number
(PID), the nice value (NI) which determines the priority of the process,
C.3. MANAGING PROCESSES C.10
and the cpu time (TIME) used up by the task. In the above example
listing, sendmail is the mail program, lmgrd is the license manager dae-
mon, CFDSd is the license server for FLOW3D program, nfsd is the NFS
daemon; all of these tasks are run by root with a user identification num-
ber (UID) of 0. Note that the ps command itself is a task.
user@machine:dir> ctrl-z
The PID number is displayed at that time. Even if you did not note it
down, you can find a list of all suspended jobs with the command
user@machine:dir> jobs
user@machine:dir> fg %n
where n is the job number produced by the jobs command (and not the
PID number!). The "fg" command brings a job to the foreground.
Except for the super user (or root), one can terminate only those pro-
cesses that belong to (or initiated by) individual users.
When used in its simplest form as above, any output that would normally
appear on the screen will be saved in a file named nohup.out in the
current directory. Wait before logging off because the nohup command
takes a moment to start the command or script you specified. If you
log off too quickly, your command or script may not run at all. Once
your command or script starts, logging off does not affect it. Note that
in order to run a script, the script file must have execute permission.
In the above script we start MATLAB in the first line and redirect any
output generated by MATLAB for the standard output ( i.e., screen during
an interactive session) to a file named out. During an interactive session,
MATLAB expects commands from the standard input ( i.e., the keyboard).
Such inputs are now taken from the script file itself as seen in the next
few lines where we execute some MATLAB functions and finally quit
MATLAB.
The contents of such a script file can be executed interactively while
logged in to a machine by simply entering the file name as
user@machine:dir> test.bat
user@machine:dir> pg /usr/local/matlab/bin/matlab
C.4. LIST OF OTHER USEFUL AIX COMMAND C.12
which will begin executing the script file at 21:00 hours. To examine a
listing of all the jobs scheduled use,
user@machine:dir> at -l
To remove a job that you have accidentally submitted, you can use,
A list of less frequently used AIX commands is given in Table C.1. You
can use either the man page feature with
or the
user@machine:dir> info
command which starts the InfoExplorer to find out about the syntax and
usage of these and other commands. The directory /usr/bin contains
all of the Unix commands.
C.4. LIST OF OTHER USEFUL AIX COMMAND C.13
command Function
at to schedule a task to start at a given time
cat to list a file
cd to change directory
diff compare two files
dosformat formats a floppy diskette using MS-DOS standards
dosread copies a DOS file from a floppy
doswrite copies a unix file to a DOS formatted floppy
find find a file
info InfoExplorer - online documentation
ksh start a Kron Shell
make a powerful UNIX make facility
mail read mail
mkdir create a directory
man display online manual pages
logout logout of current AIX session
lpq list the queue of print jobs
lpr send a print job to a network printer
lprm remove a print job from a queue
nice control job priority
nohup Don’t kill a process upon logout
pg display a file, one page at a time
ping to check if another machine is alive
pwd display present working directory
rlogin remote login to another machine
rcp remote copy files from one host to other
need to have ".rhosts" file setup
rm remove (delete) files
rmdir remove directories
rsh execute a command on a remote machine
need to have ".rhosts" file setup
rusers list remote users in the local area network
script logs a terminal session to a file
talk talk to another user currently signed on
tar archive files
telnet connect to remote hosts
whoami find out the current user
xinit start X-server
xlc c-compiler
xlC c++ compiler
xlf Fortran compiler