This action might not be possible to undo. Are you sure you want to continue?

Numerical Solution of Ordinary Differential Equations

Chapter 5

Program Description: The MATLAB function LinearODEm solves a set of linear ordinary differential equations. The first part of the function checks the number of inputs and their sizes, or values. The next section of the function performs the solution of the set of ordinary differential equations, which can he done by either the matrix exponential method [Eq. (5.40)l or the eigenvector method [Eq. (5.5311. The method of solution may he introduced to the function through the fifth input argument. The default method of solution is the matrix exponential method. The main program Example5-2.m solves the particular problem posed in this example by applying Linear0DE.m. This program gets the required input data, including the rate constants and initial concentrations of the components, from the keyboard. Then, it builds the matrix of coefficients and the vector of times at which the concentrations are to be calculated. In the last section, the program asks the user to select the method of solution and calls the function LinearODE to solve the set of equations for obtaining the concentrations and plots the results. The reader may try another method of solution and repeat solving the set of linear differential equations in this part. Program

Example5_2.m % Examples-2 .m % Solution to Example 5.2. This program calculates and plots % concentrations of the components of the system Ac->Bc->C vs % time. It calls the function LinearODE to solve the set of % linear ordinary differential equations. clear clc clf

9, Input data kl = input(' A->B , kl = ' 1 ; k2 = input 1 ' B->A , k2 = ' ) ; k3 = input(' B->C , k3 = ' 1 ; k4 = input(' C->B , k4 = ' ) ; disp( ' ' cO(1) = input(' Initial concentration of A = ~012) = input(' Initial concentration of E = ~013) = input(' Initial concentration of C = displ ' ' tmax = input(' Maximum time = ' 1 ; dt = input(' Time interval = ' 1 ; disp(' 0

,);

' ) ;

');

% Matrix of coefficients

**Example 5.2 Solution of a Chemical Reaction System
**

K = 1-kl, k2, 0; kl, k2-k3, k4; 0, k3, k 4 1 ; t = [O:dt:tmax]; % Vector of time if t(end) -= tmax t (end+l) = tmax; end

279

disp( ' ) disp ( ' 1 ) Matrix exponential method') dispi' 2 ) Eigenvector method') disp(' 0 ) Exit') method = input('\n Choose the method of solution

:

'1;

% Solution method = 1; while method c = LinearODE(K,cO,t,[I,method);% Solving the set of equations plot(t,c(l,:),t,c(2,:).'.-',t,ci3,:),'--')% Plotting the results xlabel( 'Time' ) ylabel('Concentration') legend('C-A1,'C-B','C-C') method = input('\n Choose the method of solution : ' ) ; end

**Linear0DE.m function y = LinearODE(A,yO,t,tO,method) % LINEARODE Solves a set of linear ordinary differential equations.
**

% % % % % % % % % % %

Y=LINEARODEiA,YO,T)solves a set of linear ordinary differential equations whose matrix of coefficients is A and its initial conditions are YO. The function returns the values of the solution Y at times T.

%

% % %

Y=LINEARODEiA,YO,T,TO,METHOD) takes TO as the time in which the initial conditions YO are given. Default value for TO is zero. METHOD is the method of solution. Use METHOD = 1 for matrix exponential method Use METHOD = 2 for eigenvector method Default value for METHOD is 1.

See also ODE23, ODE45, ODE113, ODElSS, ODE23S, EULER, MEULER, RK, ADAMS , ADAMSMOULTON (c) N. Mostoufi & A. Constantinides

%

% January 1, 1999 % Checking inputs if nargin<3 I isempty(=)

280

Numerical Solution of Ordinary Differential Equations

Chapter 5

error('Vector of independent variable is empty.') end if nargin<4 I isempty(t0) to = 0; end t = t - to; nt = length(t); if nargin<5 I isempty(method) method = 1; end

I

method < 1

I

method > 2

nA = length(&) ; if nA -= length(y0) error('Matrixof coefficients and vector of initial values are not of the same order.'); end yo = (y0(

:)

.' ) ' ;

%

Make sure it's a column vector

switch method case 1 % Matrix exponential method for k = 1:nt if t(k) > 0 y(:,k) = expm(A*t(k) )*yo; else ~ ( : . k= ) YO; end end case 2 % Eigenvector method [X,Dl = eig(A); % Eigenvectors and eigenvalues IX = in" (X) ; e-lambda-t = zeros (nA,nA,nt) ; % Building the matrix exp(LAMBDA.t) for k = 1:nA e-lambda-t(k,k, : ) = exp(D(k,k) * t); end % Solving the set of equations for k = 1:nt if t(k) > 0 y(:,k) = X * e-lambda-t(:,:,k) * IX * yo; else y(:.k) = YO; end end end

E5. that after long enough time. The reader is encouraged to verify the difference between the methods by repeating the solution and choosing a smaller time interval. whereas the eigenvector method involves several element-byelement operations when building the matrix eA'. the matrix exponential method is appreciably faster in the MATLAB environment than the eigenvector method.1 1 2 0 Matrix exponential method Eigenvector method ) Exit ) ) Choose the method of solution Choose the method of solution : : 2 0 Discussion of Results: The results of solution of this problem are shown in Fig. say 0. However. These results also confirm the conservation of mass principle: Because both methods of solution are exact. as expected for this special case.001.2. results obtained by these methods would be identical. and applying this to both solution methods. .lk. when dealing with a large number of equations andlor a long time vector.2 Solution of a Chemical Reaction System Input and Results 281 Initial concentration of A = 1 Initial concentration of B = 0 Initial concentration of C = 0 Maximum time = 5 Time interval = 0.Example 5. It is seen from this figure. all the component A is consumed and the components B and C satisfy the equilibrium condition CdCc = k. This is because the exponential of a matrix is performed by the built-in MATLAB function expm..

.2 Concentration profiles.4. The formulas developed for the solution of a single differential equation are readily expandable to those for a set of differential equations.5. which must be solved simultaneously. This concept is demonstrated in Sec. we develop numerical solutions for a set of ordinaq differential equations in their canonical form: with the vector of initial conditions given by In order to be able to illustrate these methods graphically. we treaty as a single variable rather than as a vector of variables. 5. In this section.282 Numerical Solution of Ordinary Differential Equations Chapter 5 Figure E5.

are listed in Table 5. x. This approach is followed in Sec. There are several functions in MATLAB for the solution of a set of ordinary differential equations.55) One method for integrating Eq. If the solution is required at specified points of x. [x.1 and 5. A similar technique could he followed here to integrate the right-hand side of Eq.]. These solvers.. The solver that one would want to try first on a problem is ode45.1.54) The left side integrates readily to obtain XI. multistep of varying order (1-5) . (5..5.3.yi = 1 =/ l f(x.2. 5. y ] = ode45('yjrime'. In Chap. is not equally spaced.*i ?. from x. with the initial values given in the vector yo. 4.m.] should be replaced by a vector containing the values of the independent variable at these Table 5. y)dx (5. and returns the values of independent and dependent variables in the vectors x and y. y). along with their method of solution. respectively. yo) solves the set of ordinaq differential equations described in the MATLAB function yqrime.5 Nonlinear Ordinary Differential Equations-Initial-Value Problems 283 We begin the development of these methods by firstrearranging Eq. x.5. y i + .I dy J'.27) andintegrating both sides between the limits of xi s x < x i + . to x. This is the technique applied in Secs.5.55) is to take the left-hand side of this equation and use finite differences for its approximation.: J. because the function controls the step size. (5.55). The vector of dependent variable.1 Ordinary differential equation solvers in MATLAB Solver ode23 ode45 ode113 ode23s odel5s Method of solution Runge-Kutta lower-order (2nd order-3 stages) Runge-Kutta higher-order (4th order-5 stages) Adams-Bashforth-Moulton of varying order (1-13) Modified Rosenbrock of order 2 Implicit.5. y)dx (5. = 1 X/ f(x. we developed the integration formulas by first replacing the functionf (x) with an interpolating polynomial and then evaluating the integral f(x)dx between the appropriate limits. This technique works directly with the tangential trajectories of the dependent variable y rather than with the areas under the function f(x. 5. . The statement [x. x.. (5.and yi I y I yi+. the interval [x.

1 The Euler and Modified Euler Methods One of the earliest techniques developed for the solution of ordinary differential equations is the Euler method.. [x. The first input to this function has to be the independent variable. x.yo)returns the solution of the set of ordinary differential equations from x. gives a "forward marching" formula for evaluating y: The forward difference term Ayj is obtained from Eq. however. The second input argument to ygrime is the vector of dependent variable. y.53) applied toy at position i: In the Euler method. when rearranged. The basic syntax for applying the other MATLAB ordinary differential equation solvers is the same as that described above for ode45. (3. that in this case.m has to be an empty variable. the third input to ygrime. It should be noted. The function ygrime.57) and (5. flag. [x. (5. 5. For example. even if it is not explicitly used in the definition of the derivative. and the additional parameters are introduced in the fourth argument. (5.5.m should return the value of derivative(s) as a column vector.284 Numerical Solution of Ordinary Differential Equations Chapter 5 points. the above series is truncated after the first term to obtain The combination of Eqs.55) is the first forward finite difference of y at position i: which. to x.: h: x . perhaps. ] . It is possible to pass additional parameters to the derivative function. at intervals of the width h.59) gives the explicit Euler formula for integrating differential equations .. The vector x in this case would be monotonic (with the exception of. This is simply obtained by recognizing that the left side of Eq. yl = ode45('ygrime'. its last interval).

. the forward marching formula in terms of backward differences is Y. Note that the first forward difference of y at i is equal to the first backward difference of y at (i + 1): Therefore.. (b)Several steps. y.If h is large the trajectory of y can quickly deviate from its true value. 7 ' Exact y Figure 5. + v~i+l (5.27) . as shown in Fig.3 The explicit Euler method of integration.63) 'Frornhere on the t e m y ' >and f(x. 5.. The accuracy of the Eulermethod can be improved by utilizing a combination of forward and backward differences. This Euler formula is rather inaccurate because it has a truncation error of only O(h2).5. The reader should rememberthat these are equal to each other through the differential equation (5.i = Y. This is demonstrated graphically in Fig 5.3b.5 Nonlinear Ordinary Differential Equationslnitial-Value Problems 285 The derivative Dyi is replaced by its equivalent y'j or f(x. (a) Single step. yJ will be used interchangeably.3a.) to give the more commonly used form of the explicit Euler method2 This equation simply states that the next value of y is obtained from the previous value by moving a step of width h in the tangential direction of y.

Eq. is obtained from Eq. 2. that is. If the set consists of nonlinear equations. the problem is much more difficult and must be solved using Newton's method for simultaneous nonlinear algebraic equations developed in Chap. (5. (5.. In the case of the Euler methods. when used in combination. because it involves the calculation of function f at an unknown value of yz+.286 Numerical Solution of Ordinary Differential Equations + Chapter 5 The backward difference term Vy.57) and (5.58) and (5. . The explicit. 5. method. 1.4. (i + I): . This conclusion can be reached by adding Eqs.63) and (5. However.32) applied to y at position Combining Eqs. the difference between the two consecutive corrected values becomes less than the convergence criterion. yielding an error of order (hi). (3. as well as the implicit.: and then using this predicted value in the implicit method to get a corrected value: This combination of steps is known as the Euler predictor-corrector (or modified .64) to obtain . forms of the Euler methods have error of order (h').65) can be viewed as taking a step forward from position i to (i + I) in a gradient direction that must be evaluated at (i + I). the problem can be solved by the application of the Gauss elimination methods developed in Chap. their accuracy is enhanced. whose application is demonstrated graphically in Fig. However. (5. When these sets are linear. Correction by Eq. as predictor-corrector. the problem can be simplified by first applying the explicit method to predict a value y j +. (5.67) may be applied more than once until the corrected value converges.64): This is called the implicit Euler formula (or backward Euler). Implicit equations cannot be solved individually but must be set up as sets of simultaneous algebraic equations.63): and utilizing (5. not much more accuracy is achieved after the second application of the corrector. .

) (5. Figure 5. by the number of terms retained in the infinite series expansion.70)can be written in a more general form as where.5 Nonlinear Ordinary Differential Equations-Initial-Value Problems 287 The terms of order (h2)cancel out because they have opposite sign.. The stability of these methods will be discussed in Sec. (5.and the positions i and (i + 1) at which to evaluate the trajectories is dictated by the accuracy required of the integration formula.69)is essentially the same as the trapezoidal mle [Eq..69) in the form that this Euler method uses the weighted trajectories of the function y evaluated at two positions that are located one full step of width h apart and weighted equally. (5.). is predicted and y'.70)is also known as the Crank-Nicolson method.. (5. Eq... is calculated.. It can be seen by writing Eq. Y. Eq.4 The Euler predictor-corrector method. In this form. in this case: k.7. It has been shown 111 that the Euler implicit formula is more stable than the explicit one.5.72) The choice of the weighting factors w. is corrected. (4. Eq. = hf(x. thus giving a formula of higher accuracy. (a) Value of y. (b) Value of y.. y j + . the only difference being in the way the function is evaluated at (xi+ . and w. 5. .731.. that is. (5.

= 0. In amore general fashion. third.5. These methods are based on the concept of weighted trajectories formulated at the endof Sec. = 0 and a. plus a number of other techniques that are variations on the Runge-Kutta theme. + w3k3 + .. .5.27) is given by the recurrence equation y.1. These are discussed in the following section. is set when (in + 1) terms are retained in the infinite series expansion of y. The value of m. 5. withincreasingly higher accuracies.k. 5.. the forward marching integration formula for the differential equation (5. .2 The Runge-Kutta Methods The most widely used methods of integration for ordinruy differential equations are the series of methods called Runge-Kutta second. which determines the complexity and accuracy of the method.288 Numerical Solution of Ordinary Differential Equations Chapter 5 This concept forms the basis for a whole series of integration formulas..k. are evaluated by These equations can be written in a compact form as where c .. and fourth order. (5. for ordinary differential equations.+] = yi + w l k l + w. + w.74) where each of the trajectories k.

5.5 Nonlinear Ordinary Differential Equations-Initial-Value Problems

289

The procedure for deriving the Runge-Kuttamethods can be divided into five steps which are demonstrated below in the derivation of the second-order Runge-Kutta formulas.

Step 1 : Choose the value of m, which fixes the accuracy of the formula to be obtained. For second-order Runge-Kutta, m = 2. Tmncate the series (5.79) after the (m + 1) term:

**Step 2: Replace each derivative of y in (5.80) by its equivalent in,f, remembering that f is a function of both x and y(x):
**

Dyj

=

f;

(5.81)

Combine Eqs. (5.80) to (5.82) and regroup the terms:

Step 3: Write Eq. (5.76) with m terms in the summation:

where

kl k2

=

h f ( x j 3Y,) hf(x, c2h. Y , + a Z 1 k l )

+

=

**Step 4 : Expand the f function in Taylor series: f(x, c2h, yi+ a 2 , k , ) =
**

+

L

+

c2hfXf a2,hfY8L O ( h 2 )

+

+

290

Numerical Solution of Ordinary Differential Equations

Chapter 5

Combine Eqs. (5.84) to (5.87) and regroup the terms:

Step 5 : In order for Eqs. (5.83) and (5.88) to be identical, the coefficients of the corresponding terms must he equal to one another. This results in a set of simultaneous nonlinear algebraic equations in theunknown constants w,,c,, and a,,.For this second-order Runge-Kutta method, there are three equations and four unknowns:

It turns out that there are always more unknowns than equations. The degree of freedom allows us to choose some of the parameters. For second-order Runge-Kutta, there is one degree of freedom. For third- and fourth-order Runge-Kutta, there are two degrees of freedom. For fifth-order Rnnge-Kutta, there are at least five degrees of freedom. This freedom of choice of parameters gives rise to a very large number of different forms of the Runge-Kuttaformulas. It is usually desirable to first choose the values of the c, constants, thus fixing the positions along the independent variable, where the functions

are to be evaluated. An important consideration in choosing the free parameters is to minimize the roundoff error of the calculation. Discussion of the effect of the roundoff error will be given in Sec. 5.7. For the second-order Runge-Kutta method, which we are currently deriving, let us choose c, = 1. The rest of the parameters are evaluated from Eqs. (5.89):

W

=w

2

= -1

a,,

=

1

2

(5.90)

With this set of parameters, the second-order Runge-Kutta formula is

This method is essentially identical to the Crank-Nicolson method [see Eq. (5.70)]

5.5 Nonlinear Ordinary Differential Equations-Initial-Value Problems

291

A different version of the second-order Runge-Kuttais obtained by choosing to evaluate the function at the midpoints (that is, c, = 112). This yields the formula

Higher-order Runge-Kutta formulas are derived in an analogous manner. Several of these are listed in Table 5.2. The fourth-order Runge-Kutta, which has an error of O(h5),is probably the most widely used numerical integration method for ordinary differential equations.

**5.5.3 The Adams and Adams-Moulton Methods
**

The Runge-Kutta family of integration techniques, developed above, are called single-step methods. The value of y,, is obtained from yj and the trajectories of y within the single step from (x,,yz)to (x,,,, y,,,). This procedure marches forward, taking single step of width h, over the entire interval of integration. These methods are very suitable for solving initial-value problems because they are self-starting from a given initial point of integration. Other categories of integration techniques, called multiple-step methods, have been developed. These compute the value of yj utilizing several previously unknown, or calculated, values of y (y,,y , ,,Y , . ~etc.) , as the hase points. For this reason, the multiple-step methods are nonself-starting. For the solution of initial-value problems, where only yo is known, the multiple-step methods must be "primed" by first utilizing a self-starting procedure to obtain the requisite number of hase points. There are several multiple-step methods, two of these, the Adams and Adams-Moultou methods, will be covered in this section. Once again, let us start by evaluating y,, by integrating the derivative function over the interval [x,, xj+,I

,

+

,

,

In order to evaluate the right-hand side of Eq. (5.55). f(x, y ) may be approximated by an nth-degree polynomial. In the Adams method, a quadratic polynomial is passed through the (x ) ,,,,y i ,), and (xZ, yi), and is used to extrapolate the value three past points, that is, (xi.2, Y , ~ ~

+l = y. = yi + -(k. + -1( k .292 Numerical Solution of Ordinary Differential Equations Chapter 5 Table 5. 2 1 + k. 6 + 2k3 + k..) + Oih3) Third order Fourth order Y..2 Summary of the Runge-Kutta integration formulas Second order Y.) + ~ ( h * ) . + 2k.

4k2 6k3 hf x i + h .+ 16 h f l x r+ h i.+ 7 7 i Runge-Kutta-Fehlberg . + 7 + ...5 Nonlinear Ordinary Differential Equations-lnitial-Value Problems Table 5. yj + I : i] 16 k4 = 2) 16 16 16 12k4 7 7 y:-+-+- k6 = k. + .2 Summary of the Runge-Kutta integration formulas (cont'd) Fifth order y.. yi) 2 k.+. = 3*1 hf x .5.. + .+ . y . = 293 y j + -(7kl 1 90 + 32k3 + 12k4 + 32k5 + 7k6) + 0(h6) k. = hf(x. y .

(5. Solution of the ordinary differential equation from the fourth point may then be continued with Eq. y) in Eq. y. another two succeeding values should be calculated by a single-step method. (5.. The value of y i + . .y. (5.+.95) shows that prior to evaluating y.+. )=~Yi . (5. (5.. y. therefore. h ( Y ~ * .. + In the Adams-Moulton method..+. In order to derive the Adams-Moulton technique.).. If we choose a uniform step size..) may he evaluated at this stage. (5.y.. and calculate the corrected value of y.. Noting that (x.55): .93) reduces to This equation would be easier to use by expanding the backward differences in terms of the function values given in Table 3.?i-2) 24 + . .55).5. the values of the function at three points before that have to be known. y).) 37f(x. such as Runge-Kutta. This procedure results in prediction of?. + + .. a second-degree backward Gregory-Newton interpolating polynomial may be applied to this problem and Eq.) . We now interpolate the function f(x. Replacing the backward differences followed by further rearrangements results in the following formula known as the Adams method for solution of the ordinaty differential equations: Eq.59f(x yi-. -xi) = h..96) is a good approximation of the dependent variable at position (i + 1). to x.. and it may be considered a function of x only. almost the correct value off(x.. using a cubic from f(x. before moving to the next step..294 Numerical Solution of Ordinary Differential Equations Chapter 5 offlx. by the integral of Eq.calculated from Eq.95).+.-2. -[55f(x. Because in an initial-value problem only the value of the function at the start of the solution interval is known. we do not stop here and correct y.55) becomes whereJ =f(x..+.. Eq.+ (yt Gregory-Newton backward interpolating polynomial over the range from xi.). we repeat the same procedure by applying a third-degree interpolating polynomial (using four past points) instead of a seconddegree polynomial to approximate f(x.. (5.

+k4]) 6 1 j = 1 .. some other technique should be applied at the beginning of the solution to evaluate y ..99) in matrix form. . two applications of the corrector is probably optimum in terms of computer time and the accuracy gained. yZz. the values of k and y. for example. .4 Simultaneous Differential Equations It was mentioned at the beginning of Sec.. = yjj + -(kl..97) should be used as predictor and corrector. (5. .. can be put in vectors and easily perform Eq.5 Nonlinear Ordinary Differential Equations-Initial-Value Problems 295 Eqs. Correction by Eq. Once again...5. yjn) This method is easily programmable using nested loops.+2k3. y j 1 . we use the set of n simultaneous ordinary differential equations: and expand. (5.n j=l.n kt] = hh(x.96)and (5. that is. the difference between the two consecutive corrected value becomes less than the convergence criterion. solution of the ordinary differential equation by this technique may start from the fifth point. +2k2... 5. However. toy. To illustrate this. . In MATLAB. the fourth-order Runge-Kutta formulas to Y < + ] .Z. 2 .5 that the methods of solution of a single differential equation are readily adaptable for solving sets of simultaneous differential equations. respectively. . 5.5. therefore.. (5. .97) may be applied more than once until the corrected value converges.

0770T - 30.2 ) 7 ~ 1 0(T3 . ~ k = 3.CO + CH. Pure acetone enters the reactor at a temperature of To = 1035 K and pressure of Po = 162 kPa.K -~~~ - Determine the temperature profile of the gas along the length of the reactor.~J1mol.0945T 0.r .(cpA XAcp) + + 'This problem was adapted from Fogler 121 by permission of the author .5 . and the temperature of external gas in the heat exchanger is constant at T.8(T .~ ( T ~ . Runge-Kutta. Apply these functions for the solution of differential equations that simulate a nonisotherm plug flow reactor. Other data are as follows: Volumetric flow rate: Volume of the reactor: Overall heat transfer coefficient: Heat transfer area: Reaction constant: Heat of reaction: vo = 0.CH.4 5 . we have to solve the material balance and energy balance equations simultaneously: dX _ .3 Vapor-phase cracking of acetone.2 9 -8 1~ .296 Numerical Solution of Ordinary Differential Equations Chapter 5 Example 5. described by the following endothermic reaction: CH. Method of Solution: In order to calculate the temperature profilein thereactor. 7 1 ~ 1 0 J1mol.298). 8 6 ~ 1 0 . and Adams-Moulton methods.K ~~~ 1 8 . takes place in a jacketed tubular reactor. Write general MATLAB functions for integrating simultaneous nonlinear differential equations using the Euler. Mole balance: dV FAo Energy balance: d~ - _ Ua(Ta - dv T) rAAHR FA. ~ . Assume constant pressure throughout the reactor. Euler predictor-corrector (modified Euler). . as described below.3: Solution of Nonisothermal Plug-Flow Reactor.35-+]]s-1 - AH. = 80770 + 6.COCH.002 m3/s v.1830T .95~10J1mol.58 exp 34222 [ [l. = 1150 K. Adams.29X3) Jlmol CpA= 26.04 Cpc = 13.= l m 3 U = 110 W / m 2 . 7 5 ~ 1 0 .63 Cpa = 20.K T~ 0.39 + + + Heat capacity of acetone: Heat capacity of ketene: Heat capacity of methane: 0.

m).2 are used for calculating a Runge-Kutta solution of the differential equations. and C is the concentration of acetone vapor at the inlet.95). The reaction rate is given as A0 In order to introduce the pair of differential equations as a MATLAB function the following definitions are assumed: Program Description: Five general MATLAB functions are written for the solution of nonlinear ordinaly differential equations. (5. andAdamsMou1ton. RK.m. It is important that this function returns the values of the derivatives (i) as a column vector. or fifth-order Runge-Kutta method. + Cpc . which has the same order of truncation error as the Adams-Moulton method. third-.m.m-The Adams-Moulton method: This function solves the set of differential equations using Eqs. The required starting points are evaluated by the fourth-order Runge-Kutta method (using the function RK. Brief descriptions of the method of solution of these five functions are given below: Euler.mThe Eulermethod: This function solves the set of differential equations based on Eq.4.m) which has the same order of truncation error as the Adams method.Cp.mThe Eulerpredictor-corrector (modified Euler) method: This function solves the set of differential equations based on Eqs.3 Solution of Nonisothermal Plug-Flow Reactor 297 where X is the conversion of acetone. MEuler. and some vectors to be used in the second part are initiated. The first input argument to all the above method functions is the name of the MATLAB function containing the set of differential equations. fourth-. MEuler.m-The Runge-Kutta methods: This function is capable of solving the set of differential equations by a second-. The formulas that appeared in Table 5.66) and (5. T is the temperature of the reactor.Adams. (5.61). which is done simultaneously in vector form.96) and (5. Vis the volume of the reactor. (5.Example 5. Adams. F A0 = CA" v0 is the molar flow rate of acetone at the inlet.mThe Adams method: This function solves the set of differential equations using Eq.m. AdamsMou1ton.m. (5. in which specific input arguments are checked. even if it is not used explicitly in the equations. The other inputs to the method functions are initial and final values of the independent .97).m. They are Euler. The next section of the function is solution of the set of nonlinear ordinary differential equations according to the specified method. a set of si~nultaneons RK. The required starting points are evaluated by the third-order Runge-Kutta (using the function RK. All these functions consist of two main sections. ACp : CP. Note that the first input argument to this function has to be the independent variable.67). The first part is initialization.

298 Numerical Solution of Ordinary Differential Equations Chapter 5 variable. Program ExampleS-3. % It is also capable of comparing different solvers. MEuler. while change clear clc 8 Input data TO = input ( ' Inlet temperature (K) PO = input(' Inlet pressure (Pa) vO = input(' Inlet volumetric flow rate (m3/s) XO = input i ' Inlet conversion of acetone VR = input ( ' Volume of the reactor (m3) Ta = input(' External gas temperature (K) U = input ( ' Overall heat transfer coefficient a = input ( ' Heat transfer area irn2/rn3) CAO = PO * (1-XO) / (8. while met clc ) fprintf ( 'in' disp( ' 1 ) Euler' disp(' 2 ) ~odifiedEuler') disp(' 3 ) Runge-Kutta') Adams ' ) disp ( ' 4 disp ( ' 5 ) Adams-Moulton') disp( ' 6 ) Comparison of methods' ) disp(' 0 ) End') .314 * TO). through the above functions. This program calculates and plots % the temperature and conversion profile of a plug-flow reactor % in which the endothermic cracking of acetone takes place. interval width. RK.m % Examplei-3. the order of the method may also be specified. h = input(' Step size = ' ) . or AdamsMoulton solvers % for solution of the pair of energy and material balances.m % Solution to Example 5.3. It is possible to pass.m. change = 1. In RK. additional arguments to the M-file describing the set of differential equations. % It can call Euler. and the initial value of the dependent variable.% Input concentration (mol/rn3) FA0 = vO * CAO. Adams. % Input molar flow rate (mol/s) fprintf('\n') fname=input(' M-file containing the set of differential equations : '). met = 1.

h.TOl . end lgnd = [lgnd '. [XO.U.TOl . ' I : end lgnd = [lgnd "'Modified Euler'' ' I .U.U.yl = Eulerlfname.[XO. [XO.O.CAO. case 2 % Modified Euler [V. a.TO. i f k > l lgnd = [lgnd '.TO.3 Solution of Nonisothermal Plug-Flow Reactor 299 met = input('\n Choose the method of solution : ' ) : if met == 6 method=input ('\n Input the methods to be compared.TO.'I.T01.Ta) . % Conversion . : ) = yll.TOl. case 5 % Adams-Moulton [V.Ta): [v.Ta): i f k > 1 lgnd = [lgnd '. end x(k.U.h. FAO.a. for k = 1:lmethod switch rnethodlk) case 1 % Euler [V. ' I .VR.m.O. end lgnd = [lgnd "'Adams-Moulton"']. lmethod = lengthlmethod).:).Example 5. ifni2 l n > 5 n = 2. end lgnd = [lgnd "'RK' int2strln) ""I.O. else method = met.yl = AdamsMoulton(fname.CAO. h.yl = MEuler(fname.Ta).TO.VR. y] = Adams (£name. i f k > 1 lgnd = [lgnd ' . FAO.CAO.FAO.'I. [XO. a. h.'I. end lgnd = [lgnd "'Adams"']. case 4 % Adams 0 .a. case 3 % Runge-Kutta n = input('\* Order of the Runge-Kutta method (2-5) = ' 1 . as a vector : ' 1 .FAO. end lgnd = 'legend('. ifk>1 lgnd = [lgnd ' .CAO. end lgnd = [lgnd '"Euler"'1.VR.

95e-6*TA2.86e-6*TA2.YI)Solves a set of ordinary differential equations by the Euler method.077*T .45.Y]=EULER('F' . X = ~(1).:) = y(2.yl = Euler (ODEfile.xf.0945*T . % Temperature k = 3.x(l:lmethod. % Temperature end if met Clf % Plotting the results subplotl2.vararginl % EULER Solves a set of ordinary differential equations by % the Euler method.:)) xlabel ( 'V/V-R'1 ylabel ( 'Temperature.TO.75e-3*(T~2-29882)-1. % Heat capacity of c dCp = CpB + CpC . % Heat cawacitv of A.m and will be called % by the selected ODE solver.plot(V/VR.m function fnc = Ex5-3-func (V. % Heat capacity of B CpC = 13.m function [x. . rA = -k * CAO * (1-X)/(l+X)* TO/T. X(%)') title('(a) Acetone Conversion Profile') subplot(2.t(l:lmethod. end Ex5-3pnc.:)) ylabel('Conversion.58*exp(34222* (1/1035-1/T) ) . The name of this function % is an input to the main program Example5-3.71e-6*TA2. h.FAO.plot(V/VR.2). .:). from XI to XF.63 + .U. < Eu1er.Ta) % Function Ex5-3-func..xi.3.XF.04 + . eval (lgnd) end end change=input('\n\nDo you want to repeat the solution with different input data (0/1)? ' ) .300 Numerical Solution of Ordinary Differential Equations Chapter 5 t(k. % Heat of reaction CpA = 26.183*T .yi. CpB = 20.1.1. (U*a* (Ta-T)+rA*dHR) / (FAO* (CpA+X*dCp) ) ]. % Reaction rate % Mole balance and energy balance fnc = 1-rA/FAO.H. % Conversion T = ~(21.CAO. % % % [X.T(K)' ) title('(b) Temperature Profile') lgnd = [lgnd ' ) ' I .1).CpA. % Rate constant ~ H R = 80770+6.y.18.30.27e-6*1TA3-298~3).M % This function contains the pair of ordinary differential % equations introduced in Example 5.a.8*1T-298)-5.39 + .XI.

yi. ODElSS. H is the length of interval and YI is the vector of initial values of the dependent variable at XI. . ODE113.P1. MEULER.) .YI) solves a set of ordinary differential equations by the modified Euler (the Euler predictor-corrector) method.XI.XF. RK.P2.xi. PI. % % % % % % % % % % % [X.H.XF. H is the length of interval and YI is the vector of initial values of the dependent variable at XI. 1999 % Initialization if isempty (h) I h == 0 h = linspace(xi. [X.varargin) % MEULER Solves a set of ordinary differential equations by % the modified Euler (predictor-corrector)method. See also ODE23. ) allows for additional arguments which are passed to the function F(X. . Constantinides % January 1.h. % Make sure it's a column vector x = [xi:h:xfl. Mostoufi & A. The equations are given in the M-file F. ODE45.H. . [X. .Example 5.i) + d(i) * feval(ODEfile. .P2.')'.) .xf).Pl.XI. ADAMS. from XI to XF.yl = MEuler(ODEfile.M.3 Solution of Nonisothermal Plug-Flow Reactor % % % % % % 301 The equations are given in the M-file F. .YI..varargini:)). . .Y]=MEULER('F'.YI=EULER('F'. ADAMSMOULTON % % % % (c) N.y(:. end d = diff (x): % Vector of x values % Vector of x-increments y(:. if x(end) -= xf x(end+l) = xf.m function [x.Yl=MEULER( 'F'. end yi = (yi(:). ODE23S..xf.YI.P2. end MEu1er.2.x(i) .Pl.l) = yi: % Initial condition % Solution for i = l:length(x)-1 y(:.) allows for additional arguments which are passed to the function F(X.XF. .M.i) .i+l) = y(:.H.XI.P2.

.

y = ( 1 isempty(n) I n < 2 1 n > 5 ( : ) . y(:.i)..i).. k3 = d(i) * feval(ODEfile.i).i) + (kl+Z*k2+2*k3+k4)/6: . end if nargin == 5 n = 2.y(:. % Make sure it's a column vector % Vector of x values x = 1xi:h:xfl. varargini:}).y(:.xli+l).varargin{:}). Constantinides % Initialization if isempty (h) 1 h == 0 h = linspace (xi.i) + (kl+k2)/2. end n = fix (n) .varargin{:}).l) = yi: % Solution % Vector of x-increments % Initial condition switch n % 2nd-order Runge-Kutta case 2 for i = l:length(x)-1 kl = d(i) * feval(ODEfile.i)+kl.y(:. yl:.i+l)= y(:.y(:.i)+2*k2-kl.. . k2 = d(i) * feval(ODEfile.x(i) . .x(i)+d(i)/2.i)+kl/2.x(i).y(:. k4 = d(i) * feval(ODEfile.varargin{:}).i)+k3.3 Solution of Nonisothermal Plug-Flow Reactor % (c) N. k2 = d(i) * feval(ODEfile.varargin{:)).x(i)+d(i)/2. varargin(:)).i+l) = yl:... . xf ) .xli)+d(i)/2. end % 4th-order Runge-Kutta case 4 for i = l:length(x)-1 kl = d(i) * feval(ODEfile. 1999 303 A. k2 = d(i) * feval(ODEfile.varargin{:}). y(:.x(i+l).varargin{:}). vararginI:}): k3 = d(i) * feval(ODEfile.i+l) = y ( : .Example 5. end d = diff(x). Mostoufi & % January 1. y(:.i)+k1/2.i) + (k1+4*kZ+k3)/6.y(:. if xlend) -= xf x(end+l) = xf. end % 3rd-order Runge-Kutta case 3 for i = l:length(x)-1 kl = d(i) * feval(ODEfile.y(:.y(:.i)+k2/2..y(:.x(i+l).x(i).

3 W / + . ) allows for additional arguments which are passed to the function F(X.i)+3*kl/l6+k2/16. .XF. . ODE23S. Mostoufi January 1. . 1999 & % % % % % % A.i)+k3/2. 6*k3/7-l2*k4/7+8*k5/7. [X.P1.varargin{:)).Y]=ADAMS('F1.i)+k1/7+4*k2/7+.i) + (7*k1+32*k3+12*k4+32*k5+7*k6) /go.y(:.. . from XI to XF.yi.M.. The equations are given in the M-file F. Constantinides % Initialization if isempty (h) I h == 0 h = linspace(xi.xf). ODE45.y(:.x(i) . % % % % % % % % [X.304 Numerical Solution of Ordinary Differential Equations Chapter 5 end % 5th-order Runge-Kutta case 5 for i = l:length(x)-1 kl = d(i) * feval(ODEfile.YI) solves a set of ordinary differential equations by the Adams method.x(i)+3*d(i)/4.xf. k5 = d(i) * feval(ODEfile. RK. varargin{:l). . varargin(:)).y(: . k6 = d(i) * feval(ODEfile. . ..P2.H. H is the length of the interval and YI is the vector of initial values of the dependent variable at XI. ADAMSMOULTON (c) N. MEULER. end y = y i :' % Make sure it's a row vector x = [xi: h:xf] ' .XI.x(i+l) . varargin(:l).H.y(:.h.i+l) = y(: .. . end end Adams. ) . y(:.m function [x.YI.y(:. EULER. ODElSS.y(: .XI. k2 = d(i) * feval(ODEfile. varargin(:)).. 6*k3/16+9*k4/16. % Vector of x values if x(end) -= xf x(end+l) = xf. ODE113.i) .. .i) +k1/2.yl = Adams(ODEfile.XF. k4 = d(i) * feval(ODEfile.P2. i ) . . k3 = d(i) * feval(ODEfile. See also ODE23. . varargini:)).x(i)+d(i)/2.Pl.xi.YI=ADAMS('F1.x(i)+d(i)/2.x(i)+d(i)/4.varargin) % ADAMS Solves a set of ordinary differential equations by the % Adams method.

**Example 5.3 Solution of Nonisothermal Plug-Flow Reactor
**

end d = diff(x1; % Vector of x-increments

% Starting values

305

**[a,bl=RK(ODEfile,x(l),x(3),h,yi,3,varargin{:}1; y(:,1:31 = b; for i = 1:3 : i = feval(ODEfile,x(i),y(:,i1,varargin{:I1; end
**

% Solution

**for i = 3:length(x)-1 y(:,i+l) = y(:,il + d(i)/12 * (23*f(:,il - 16*f (:,i-1)+ 5*f(:,i-2)); f ( : ,i+l) = feval(ODEfile,x(i+l) ,y(:,i+l).varargini: I 1 ; end
**

AdnmsMou1ton.m

**function [x,yl = AdamsMoulton(ODEfile,xi,xf,h,yi,vararginl % ADAMSMOULTON Solves a set of ordinary differential equations by
**

%

the Adams-Moulton method. [X,Yl =ADAMSMOULTON('F' ,XI,XF,H,YI)solves a set of ordinary differential equations by the Adams-Moulton method, from XI to XF. The equations are given in the M-file F.M. H is the length of interval and YI is the vector of initial values of the dependent variable at XI. [X,Y]=ADAMSMOULTON( 'F' .XI,XF,H,YI, PI,P2,. . . ) allows for additional arguments which are passed to the function F(X,Pl,F2 , . . . I. See also ODE23, ODE45, ODE113, ODElSS, ODE23S, EULER, MEULER, RK, ADAMS

% % % % % % %

%

% %

%

% %

% (c) N. Mostoufi & A. Constantinides % January 1, 1999 % Initialization if isempty (hl 1 h == 0 h = linspace (xi, xf) ; end

yi

=

( y : 1 .'1 '

;

**8 Make sure it's a column vector
**

% Vector of x values

x = [xi:h:xfI7; if x(end1 -= xf x(end+l) = xf;

306

end d = diff(x);

%

Numerical Solution of Ordinary Differential Equations

Chapter 5

%

Vector of x-increments

**starting values [a,bl = RK(ODEfile,x(l),x(4),h,yi,4,varargini:)); y(:,1:4) = b; for i = 1:4 f(:,i) = feval(ODEfile,x(i),y(:,i) ,varargin{:]); end
**

% Solution

**for i = 4:length(x)-1 % Predictor y(:,i+l) = y(:.i) + d(i)/24 * (55*f(:,i) - 59*f(:,i-1) . . . + 37*f ( : ,i-2) - 9*f(:,i-3)); : i + = feval(ODEfile,x(i+l).y(:,i+l),varargin(:J); % Corrector y(:,i+l) = y(:,i)+ d(i)/24 * (9*f(:,i+l)+ 19*f(:,i) . . . - 5*f(:,i-1)+ f(:,i-2)); f(:,i+l) = feval(ODEfile.x(i+l),y(:,i+l),varargin(:J); end
**

% Solution

for i = 4:length(x)-1 % Predictor y(:,i+l) = y(:,i) + d(i)/24 * (55*f(:,i)- 59*f(:,i-1) . . . + 37*f(:,i-2) - 9*f(:,i-3)); f(:,i+l) = feval(ODEfile,x(i+l) ,y(:,i+l),vargini:]); % Corrector y(:,i+l) = y(:,i) + d(i)/24 * (9*f(:.i+l)+ 19*f(:,i) . . . - 5*f(:,i-1) + f(:,i-2)); f : + l = feval(ODEfile,x(i+l),y(:,i+l),varargin{:)); end

Input and Results

Inlet temperature (K) Inlet pressure (Pa) Inlet volumetric flow rate lm3/s) Inlet conversion of acetone Volume of the reactor (m3) External gas temperature ( K ) Overall heat transfer coefficient Heat transfer area (m21m3) M-file containing the set of differential equations

:

'Ex5-3-func'

**Example 5.3 Solution of Nonisothermal Plug-Flow Reactor
**

Step size

=

307

0.00003

1 ) Euler 2 ) Modified Euler 3 ) Runge-Kutta 4 ) Adams 5 ) Adams-Moulton 6 Comparison of methods 0 ) End

Choose the method of solution : 6 Input the methods to be compared, as a vector Order of the Runge-Kutta method (2-5) = 2

1 ) Euler 2 ) Modified Euler 3 ) Runge-Kutta 4 ) Adams 5 ) Adarns-Moulton 6 1 Comparison of methods 0 1 End

:

[I, 3, 41

Choose the method of solution : 0 Do you want to repeat the solution with different input data (0/1)?0

Discussion of Results: The mole and energy balance equations are solved by three different methods of different order of error: Euler [O(h2)],second-order Runge-Kutta [O(h3)], and Adams [O(h4)]. Graphical results are given in Figs. E5.3a and b.' At the beginning the temperature of the reactor decreases because the reaction is endothermic. However, it starts to increase steadily at about 10% of the length of the reactor, due to the heat transfer from the hot gas circulation around the reactor. It can be seen from Figs. E5.3a and b that there are visible differences between the three methods in the temperature profile where the temperature reaches minimum. This region is where the change in the derivative of temperature (energy balance formula) is greater than the other parts of the curve, and as a result, different techniques for approximation of this derivative give different values for it. The reader is encouraged to repeat this example with different methods of solution and step sizes.

When running Example5_3.m, solution results will be shown on the screen by solid lines of different color. However, results for the three different methods used here are illustrated by different line type in Figs. E53a and h in order to make them identifiable.

such as Pontryagin's maximum principle or the calculus of variations 4. . Discretization of nonlinear elliptic partial dirferential equations [31. To mention only a few examples: 1. Thereare many chemical engineering applications that result in ordinary differential equations of the boundary-value type.3 Conversion and temperature profiles for Example 5. Application of rigorous optimization methods. Heat and mass transfer in boundary-layer problems 3. Diffusion with chemical reaction in the study of chemical catalysis or enzyme catalysis 2.308 Numerical Solution of Ordinary Differential Equations (a) Acetone Conversion Profile Chapter 5 100 (b) Temperature Profile 10801 1 F 1060 $ 1050 Adams Figure E5. Ordinary differential equations with boundary conditions specified at two or more points of the independent variablc areclassifiedas boundary-valueprohlems.3.

This problem can be transformed to the canonical form (5. y. 5.. the .. .100) by the appropriate substitutions described in Sec. separated or mixed.. dx .100) where the boundary conditions are split between the initial point x. These are the shooting method. . The canonical form of a two-point boundary-value problem with linear b o u n d q conditions is 2 = & ( x . we have chosen to discuss algorithms that are applicable to the solution of nonlinear (as well as linear) boundaryvalue problems. The first r equations have initial conditions specified and the last (n . In this section. . The last two methods will he discussed again in Chap. a (5. and the collocation methods. j = 1 .3.) sor: x r: xi .finite difference method. and the boundary conditions could be linear or nonlinear. The system equations in these problems could be linear or nonlinear.6 Nonlinear Ordinary Differential Equations-Boundary-Value Problems 309 The diversity of problems of the boundary-value type have generated a variety of methods for their solution. and the final point xi. twopoint or multipoint. ..r) equations have final conditions given: A second-order two-point boundary-value problem may be expressed in the form: subject to the boundary conditions a0y(x0) + boy '(so) = Y.. Comprehensive discussions of the solutions of boundary-value problems are given by KubiEek and HlavAEek [3] and by Aziz [4].5. . 6 in connection with the solution of partial differential equations of the boundary-value type.104) where the subscript 0 designates conditions at the left houndary (initial) and the subscript f identifies conditions at the right boundary (final).. (5. y. 2 . y .

In this section.. the calculated final values are compared with the boundary conditions and the guessed initial conditions are corrected if necessary. We develop the Newton method for a set of two differential equations with split boundary conditions yl(x0) = Y. In this method. This general algorithm forms the basis for the family of shooting methods. At the end. 5. at xf is designated as y2(xf.110) . (5.109) If the system equations are integrated forward.(x.310 Numerical Solution of Ordinary Differential Equations Chapter 5 5.5). misses its target at xi.108).1 The Shooting Method The shooting method converts the boundary-value problem to an initial-value one to take advantage of the powerful algorithms available for the integration of initial-value problems (see Sec. it does not satisfy the boundary condition of (5.1 10) to = Yz. This procedure is repeated until the specified terminal values are achieved within a small convergence criterion. Y~(XO =) Y (5.5. Since the value of y . y).. the calculated value of y. The desirable objective is to find the value of y which forces y. ( x . (5. These may vary in their choice of initial or final conditions and in the integration of the equations in one direction or two directions.6. ) was only a guess. y2(xf. the unspecified initial conditions of the system differential equations are guessed and the equations are integrated forward as a set of simultaneous initialvalue differential equations. the trajectory of y. 5. (5. we develop Newton's technique. which is the most widely known of the shooting methods and can be applied successfully to boundary-value problem of any complexity as long as theresulting initial-value problem is stable and a set of good guesses for unspecified conditions can be made [3]. the two trajectories may look like those in Fig.107) We guess the initial condition for y..that is. y) to satisfy the specified boundary condition. that is. For the given guess of y. Y ) Rearrange Eq..

that is. for the trajectory of y.5 Forward integration using a guessed initial condition y. The 0 designates the known boundary points.5. Eq. (5. .112) becomes Truncation and rearrangement gives Figure 5.6 Nonlinear Ordinary Differential Equations-Boundary-Value Problems 311 The function +(y) can be expressed in a Taylor series around y : In order for the system to converge. to hit the specified boundary value of x/: Therefore.

. taking its partial derivative.117) The value of Ay is the correction to be applied to the guessed y to obtain a new guess: (Y).111)]. Solution of the set of differential equations continues with the new value of y [calculated by Eq. (5.115). we obtain where 6y is the difference between the specified final boundary value y.. and the last (n .118) In order to avoid divergence it may sometimes benecessary to take a fractional correction step by using relaxation.r) equations havefinal conditions given: In order to apply Newton's procedure to integrate the system equations forward. = (Yloid + 'Y (5.(xf3 Y ) - yz.312 Numerical Solution of Ordinary Differential Equations Chapter 5 The reader should be able to recognize this equation as a form of the Newton-Raphson equation of Chap. (5.119)l until lAyl < E.1 (5. The algorithm can now he generalized to apply to a set of n simultaneous system equations: whose boundary conditions are split between the initial point and the final point. Using the definition of @(y)[Eq.r) initial conditions are guessed as follows: . the missing (n . 1. (5. The first r equations have initial conditions specified. and combining with Eq.$ and the calculated final value y.(x/. y) obtained from using the guessed y: 6~ = -1?. that is..

121) either numerically or analytically. (Y). (5. The correction Ay to be applied to y is calculated from Eq.1 16)] is evaluated: The correction of the guessed initial values is implemented by the equation Ay = [J(x.l) I E. until min(iAy.. (5. 2.119) The shooting method algorithm using the Newton technique is outlined in the following five steps: 1. In the case when final conditions are specified for more than half the total number of differential equations. 4.100) are integrated forward simultaneously.. Evaluate the Jacobian matrix from Eq.100) with the given initial conditions (5.101) and the guessed initial conditions (5. the Jacobian matrix [equivalent to the derivative term in Eq. The system equations (5. (5.6 Nonlinear Ordinary Differential Equations-Boundary-Value Problems 313 The system equations (5.122).120). At the right-hand boundary (xf)..122) where the vector 6y is the difference between the specified final boundav values and the calculated final values using the guessed initial conditions The new estimate of the guessed initial conditions is then evaluated from Eq. The missing initial conditions of the system equations are guessed by Eq.. Steps 2 and 3 are repeated. The new value of y is obtained from Eq.5.r)1~'6~ (5.119). 3. = (Y). each time with a corrected value of y.118) in the vector form. we may simply reverse . Note that the number of differential equations with final boundary conditions is not in any case more than half of the total number of equations. (5. (5. (5. where E is the convergence criterion.120) are integrated simultaneously in the forward direction. 5.id + pAy 0 < p s 1 (5.

The application of the Newton technique in the shooting method by the above algorithm is demonstrated in Example 5.4: Flow of a Non-Newtonian Fluid.4a. results in where APIL is the pressure drop gradient along the pipe and the shear stress is expressed as Therefore. y is the shear rate.4. p.4a . Write a general MATLAB function for solution of a boundary value problem by the shooling method using the Newton's technique.. = 0 Symmetry: dvz dr ~~ ~ r = ~ -= 0 The required data for the solution of this problem are: Figure E5. (1) is a second-order ordinary differential equation. Eq. E5. Example 5.31 4 Numerical Solution of Ordinary Differential Equations Chapter 5 the integrating direction and as a result obtain fewer number of final conditions. v. is the characteristic time. is the zero shear rate viscosity. Apply this function to find the velocity profile of a non-Newtonian fluid that is flowing through a circular tube as shown in Fig. assuming the tube is very long so that end effect is negligible. t. Also calculate the volumetric flow rate of the fluid. The momentum balance for this flow. The viscosity of this fluid can he described by the Carreau model [5]: where p is the viscosity of the fluid. and n is a dimensionless constant. which should be solved with the following boundary conditions: No slip at the wall: r = R.

We designate this guess. . J l v '= 114 (7) . but the initial value y./v where v' = ( .4 Flow of a Non-Newtonian Fluid 315 Method of Solution: First we define the following two variables: Dimensionless distance: Dimensionless velocity: T- = rlR ' i$ = v. (2). (2) is the given as The set of nonlinear ordinary differential equations (3) and ( 4 ) should be solved with the following boundary conditions: The initial value y. In order to obtain the canonical form of Eq. . in accordance with Eq.A P ) R ~ I L ~Eq.(O) is known.120). = i$ The canonical form of Eq.A P ) R 2 / 4 L p . ( 1 ) can beexpandedandrearrangedin its dimensionless form into the following second-order differential equation: where h = t.(O) must he guessed. we apply the following transformation: Y. as follows: y2(0)= y = [ ( . (5.Example 5.v'lR.

Eq. (5.316 Numerical Solution of Ordinary Differential Equations Chapter 5 The right-hand side of Eq. using the known and guessed initial conditions. (5. the integration step size. Once the velocity profile is determined. If these conditions are not met. the vector of final conditions. also. (3)-(6)] 2.m is developed to solve a set of first-order ordinary differential equations in a boundary-value problem using the shooting method. Eq. From the above list.123) for calculation of the 6y vector 5. and the function assumes default values for each of the above variables. The inputs to the function are the name of the file containing the set of differential equations. the number of equations should be equal to the total number of boundary conditions (initial and final). in forward direction. the flow rate of the fluid can be calculated from the following integral formula: R Q = [2nrvzdr 0 Program Description: The MATLABfunction sho0ting. the order of Runge-Kutta method. introducing the integration step size. It then sets the differentiation increment for the approximate initial conditions and consequently evaluates the elements of the Jacobian matrix. The complete set of equations for the solution of this two-pointboundary-value problem consists of: 1. by differentiating using forward finite differences method. the vector of guesses of initial conditions for those equations who have final conditions.m begins with checking the input arguments. and the convergence criterion.121) for construction of the Jacobian matrix 4. if necessary.4. The next section in the function is Newton's technique. At the end of this section. The numher of guessed initial conditions has to he equal to the number of final conditions. lower and upper limits of integration interval. [Eq. (7) corresponds to the velocity of the fluid at the center of the pipe if it was a Newtonian fluid with the viscosity p . The guessed initial condition for y. The function shooting. . the vector of initial conditions. the relaxation factor. Eqs. The structure of this function is very similar to that of the function Newt0n. and the convergence criterion are optional. (5. the order of Runge-Kutta method.122). column-wise. the approximate initial conditions are corrected according to Eqs. the relaxation factor. . This procedure begins with solving the set of differential equations by the Runge-Kntta method. It is important to note that the function sho0ting.119) for correcting the guessed initial conditions. The four system equations with their known boundary values [Eqs. (5. This procedure is repeated until the convergence is reached for all the final conditions. (7)] 3. the function gives aproper error message on the screen and stops execution.122) and (5.1 19) and (5.m requires to receive the values of the set of ordinary differential equations at each point in a column vector with the values of the .m developed in Example 1.

equations : 0 . It uses the function SHOOTING to solve the one-dimentional equation of motion which is rearranged as a set of boundary-value ordinary differential equations.yl = shooting(fname.n. (3) and (4) at a given point.vmaxO/vmax. This proqram calculates and plots the velocity profile of a non-Newtonian fluid flowing in a circular pipe. The first function evaluated is that of Eq. fname = inputl'\n M-file containing the set of differential '1. ) .Example 5.m evaluates the values of the set of Eqs. Program % % % % 8 % Examples-4. clear ClC c1f % Input data R = inputl' Inside diameter of the pipe (m) = ' 1 .h.:)*vstar. m a x O = dP*RA2/(4*mu0).s) = tl = input(' Characteristic time of the fluid is) = . = '1. [ I .h/100. the initial condition of which is known. It is also important to pass the initial and final conditions to the function in the order corresponding to the order of equations appearing in the file that introduces the ordinary differential equations. [ I . The default values of the relaxation factor and the convergence criterion are used in this example. % Radial position % Velocity profile . r = eta*R. The program then calls the function shooting to solve the set of equations and finally.O. The main program Example5-4. % Initial guess of velocity % solution of the set of differential equations [eta. it shows the value of the flow rate on the screen and plots the calculated velocity profile. vstar = 4*vmax0. . vz = y(2. .m Solution to Example 5.m asks the reader to input the parameters required for solution of the problem.4. followed by those whose final conditions are fixed.4 Flow of a Non-Newtonian Fluid 317 equations whose initial conditions are known to he at the top. dP = input(' Pressure drop gradient (Pa/m) = ' 1 . order. order = inputl' Order of Runge-Kutta method h = input(' Step size = ' 1 . The function Ex5-4frmc.O.lambda). mu0 = input(' Zero shear rate viscosity of the fluid 1Pa.l. n = input(' The exponent n from the power-law = ' ) . lambda = tl*vstar/R. (3)..

.RHO.4.Y]=SHOOTING('F'. y. % Make it a column vector sh0oting.GAMMA) integrates the set of ordinary differential equations from XO to XF. Additional parameters PI. Constantinides % January 1. . The equations are described in the M-file F.YO. See also COLLOCATION. Mostoufi & A.xf. lambda) % Function Ex5-4-func.r. P2. and starting guesses.Q*lOOO) % Plotting the results plot(100O*r. YO. f = f'.YO.XF.P2. and GAMMA are the vectors of initial conditions.XO.XF.h. % % % % % % % % % % % % % [X.m function [x. RHO.*vz). using the 4th-order Runge-Kutta method. . RK % (c) N. . 2 £ lit/s \n'.M % This function introduces the set of ordinary differential % equations used in Example 5.vz) ylabel( 'v-z (m/s) ') xlabel ( 'r (mm)' ) Ex5_4func. The function returns the independent variable in the vector X and the set of dependent variables in the matrix Y . % % % % % [X.M..YF. . are passed directly to the function F.ORDER. or TOL to use the default value.XO. rho.varargin) %SHOOTING Solves a boundary value set of ordinary differential % equations by shooting method using Newton's technique.yf. .GAMMA.m function f = Ex5-4-func (eta.TOL. YF.tol. and uses relaxation factor RHO and tolerance TOL for convergence test.Yl=SHOOTING('F'..) applies the ORDERth-order Runge-Kutta method for forward integration.xO. H is the step size.yl = shooting(ODEfile. 1999 % Initialization if isempty(h) I h == 0 . . respectively. Pass an empty matrix for ORDER.YF.yO.order. % Flow rate fprintf('\n Volumetric flow rate = % 4 .gammaO. final conditions.H.P1.318 Numerical Solution of Ordinary Differential Equations Chapter 5 Q = Z*pi*trapz(r.n.H.

01. x f. [ y o . if length(ftest1 -= n error(' The number of equations is not equal to the number of boundary conditions. iter = 0. end if nargin < 9 1 isempty(rh0) rho = 1. end if nargin < 10 1 isempty(tol1 to1 = le-6.gammanew)) > to1 & iter < maxiter iter = iter + 1. % Make sure it's a column vector % Make sure it's a column vector yf = lyf(:). end yo = (yo(:). % Make sure it's a column vector % Checking the number of guesses if length(yf) -= length(gamma0) 319 error(' The number of guessed conditions is not equal to the number of final conditions. .') end gammal = gamma0 * 1. % Newton's technique while max(abs(gamma1 .') end r = length(y0). else dganuna(k) = 0. [x.')'.4 Flow of a Non-Newtonian Fluid h = (xf .order. gammal = gammanew. fnk = y(r+l:n. gammanew = gamma0.. maxiter = 100. gamma01 .xO.')'.xi)/99. .')'. x O [yo .Example 5.end). % Number of boundary conditions % Checking the number of equations £test = feval (ODEfile. end if nargin < 8 1 isemptylorder) order = 4. % Number of initial conditions n = r + lengthlyfl.y] = ~ ~ ( ~ ~ ~ f i l e .varargin{:1). gamma0 = (gammaO(:).varargin{: 1).1. % set d(gamma) for derivation for k = l:length(gammal) if gammal(k) -= 0 dganunalk) = gammal(k) / 100.gamma11 h.

varargin{:)).dgamma(k).01 Volumetric flow rate = 2.91 Us.end) . the lower limit of integration is set to h1100. a very small value close to zero should be used in such a situation. which is negligible with respect to the dimension of the pipe.1 Pressure drop gradient (Pa/m) = 20e3 Zero shear rate viscosity of the fluid (Pa.xO.320 end end Numerical Solution of Ordinary Differential Equations Chapter 5 % Calculation of the Jacobian matrix a = gammal.IyO.4b. and the velocity profile is shown in Fig.k)= (fnka . It should be noted that because there is the term llq in Eq. . jacob(:.rho * inv(jacob) * (fnk . E5.s) = 102 Characteristic time of the fluid (s) = 4. the lower limit of numerical integration cannot be zero.l*tolI): else gammanew = gammal . end end if iter >= maxiter disp('Warning : Maximum iterations reached.xf.36 The exponent n from the power-law = 0.order.fnk) / dgamma(k1: a(k) = garnmal(k) . fnka = ya(r+l:n.375 M-file containing the set of differential equations Order of Runge-Kutta method = 4 Step size = 0. l. [xa.91 lit/s : 'Ex5-4Lfunc' Discussion of Results: The volumetric flow rate of the fluid in this condition is calculated to be 2.h. instead.yal = RK(ODEfile. end % Next approximation of the roots if det(jacob) == 0 gammanew = gammal + max([abs(dgamma).yf).') end Input and Results Inside diameter of the pipe (m) = 0. In the main program Example5-4. for k = 1:n-r a(k) = gammal(k) + dgarnma(k1. a]. (Z).

thus converting the differential equations to a large set of simultaneous nonlinear algebraic equations.2 The Finite Difference Method Thefinite-difference method replaces the derivatives in the differential equations with finite difference approximations at each point in the interval of integration.1 - 0.6 Nonlinear Ordinary Differential Equations-Boundary-Value Problems 0.12- 0. the set of two differential equations: with split boundary conditions: .5.02 0 10 20 30 40 50 r imm) 60 70 80 40 100 Figure E5. we use. To demonstrate this method. 5.08 - - 2o m >- owODZ - 0- -0.4b Velocity profile for nowNewtonian fluid.14 321 0. as before.6.

(4. described in Chap. Combining Eqs. for a practical engineering problem. a good initial guess of all the values of yg. 1. On the other hand. These form a set of 2n simultaneous nonlinear algebraic equations in (2n + 2) variables. we could have used Eq. In either case. this method is more difficult to apply than the shooting method.322 Numerical Solution of Ordinary Differential Equations Chapter 5 Next. They recommend that the finite difference method be used only for problems that are too unstable to integrate by the shooting methods. the solution can he obtained by straightforward application of matrix inversion or the Gauss elimination procedure. (5. that the problem of solving a large set of nonlinear algebraic equations is not a trivial task. and it involves the evaluation of the (2n x 2n) Jacobian matrix. The two boundary conditions provide values for two of these variables: Therefore. (4.125) for i = 0. . It requires. the resulting set of simultaneous algebraic equations will also he linear. however.106) we obtain We divide the interval of integration into n segments of equal length and write Eqs.2. (4. the system of 2n equations in 2n unknown can be solved using Newton's method for simultaneous nonlinear algebraic equations. . .124) with (5. (5.41). .33).33): For higher accuracy. In such a case.instead of Eq.n .1. . It should be emphasized. which has error of order (h2). first. we express the derivatives of y in terms of forward finite differences using Eq. KubiEek and HlaviEek [3] state that computational experience with the finite difference technique has shown that. if the differential equations are linear. the steps of obtaining the solution to the boundary-value problem are identical. 1.

(5.126) and substitute in Eqs..6. x. that is. choosing a function.(x)) m = 1.3 Collocation Methods These methods are based on the concept of interpolation of unequally spaced points. P2.127) We then form the residuals: .6 Nonlinear Ordinary Differential Equations-Boundary-Value Problems 323 5. (5.(x) of Eq.(x)...5.2 (5. pI.. Let 11s again consider the set of two differential equations: with split boundary conditions: Suppose that the solutions y.(x. and determining the coefficients of that function from a set of base points. that approximates the solution of a differential equation in the range of integration..106): P '. which we call trial functions: We take the derivatives of both sides of Eq.(x) and y. (5.(x) = f.106) can be approximated by the following polynomials. usually a polynomial. I x < x.

2 ) of the polynomials P. . the integral (5. the polynomials are exact solutions of the differential equations at those collocation points (note that x. = x. The collocation method chooses the weighting functions to be the Dirac delta (unit impulse) function: which has the property that x! S a ( x ) G ( x . that is. {x.128) and (5.133) contains the (2n + 2 ) yet-to-be-determined coefficicnts {c. This technique is called the method of weighted residuals.( I i = 0 . .(x) to make the residuals as small as possible over the range of integration of the differential equation. . At x = x . I i = 0.we have This implies that at a given number of collocarion points.R. . the coefficients of the polynomials (5.129) becomes S WkRm( x )d x I ! I " = Rm(x. I .126) are chosen so that Eq. the closer the trial [unction would resemble the true solution y. (5. : .x.. Eq. I k = 0. .) = 0 Combining Eqs. .)dx '0 = a(x. .129) where W.2) of the polynomials. The larger the number of collocation points. m = 1. m = 1. n. are weighting functions to be chosen. Because it is necessary to satisfy the boundary conditions of the problem. This is accomplished by making the following integral vanish: W... (5.) Therefore.324 Numerical Solution of Ordinary Differential Equations Chapter 5 The objective is to determine the coefficients {em. These can be calculated by choosing (2n + 2) collocation points. . n ] .(x) of the differential equations. . 1.. two collocation points are already fixed in this case of boundary-value problem. .. n.132).(x) d x 20 = 0 (5.).133) is satisfied.. (5. . 1.

137) For a more complete discussion of orthogonal collocation methods see Pinlayson [I].(x. to choose the collocation points at equidistant intervals. are yet unknown.(x) = 1-0 am..(x) to he the linear combination "+I y.2 (5. which is an extension of the method just described. The orthogonal collocation method.)) = 0 Note that we have also written Eq. The solution of this problem requires the application of Newton's method (see Chap.136a) and for x =x. provides a mechanism for automatically picking the collocation points by making use of orthogonal polynomial^.).136) constitute a complete set of (2n + 2) simultaneous nonlinear equations in (2n + 2) unknowns. as the development of interpolating polynomials and finite differences were all based on expanding the function in Taylor series (see Chap.(x) and y.f l ( x l . and y.133) for each of these points: l . (5.133) forx =x. 3).136h) because the values y. P]. in Eq.: Therefore.p.. it is more advantageous to locate the collocation points at the roots of appropriate orthogonal polynomials."(x. P. (5.. (5. 1) for simultaneous nonlinear equations. we have the freedom to choose the remaining (2n) internal collocation points and then write Eq.=x..6 Nonlinear Ordinary Differential Equations-Boundary-Value Problems 325 and at x = x. (5. however. Eqs. in Eq.5. This is not at all surprising.134)-(5. .. as the following discussion shows. In fact. " x l . then the collocation method is equivalent to polynomial interpolation of equally spaced points and to the finite difference method. (5. If the collocation points are chosen at equidistant intervals within the interval of integration.^ This method chooses the trial functions y.. It is not necessary.(x) m = 1.

to z. (5..71.. The standard interval of integration for Legendre polynomials is [-I. c. I j = 0.(x) is chosen to be the Legendre set of orthogonal polynomials [see Table 3. 11 and vice versa.-x. Therefore..I and .92) is used to transform the Legendre polynomials to the interval [x. .1 .326 Numerical Solution of Ordinary Differential Equations Chapter 5 of a series of orthogonal polynomials Pi(x): P. (5. are chosen so that the polynomials obey the orthogonality condition defined in Sec. ( 2 . the weight w(x) is unity. we use z as the independent variable of the Legendre polynomials to stress that the domain under study is the interval 1 . Hereafter. .. n + I ) .. The location of the n internal collocation points ( z . + c.) are determined from .x This set of polynomials can be written in a condensed form: The coefficients c .) z 2 + (xitx") 2 (5.. xi]. The transformation equation (4. 11. xJ corresponds to a value of z in the interval [-I.140) When P.(x) = = c.. 1.141) Eq.106)-(5.(x) P. 3. = .(xd )x = 0 i + j (5. which applies to our problem at hand: x = (x.10: b w(x)pi(x)p.... z = 1 ) .141) relates the variables x and z so that every value of x in the interval [x. 11.108)has (2n + 2) collocation points. using x or z as independent variables is equivalent.. including the two known boundary values (z. The derivatives with respect to x and z are related to each other by the following relation: The two-point boundary-value problem given by Eqs.

= C Q ' y .I ~= . (5. (5.6 Nonlinear Ordinary Differential Equations-Boundary-Value Problems 327 the roots of the polynomial P.(z)= 0. Eqs.143)may be presented in matrix notation as Y . = Ay.= Cd.)as +1 where the terms of the polynomials have been regrouped.c d .5. The derivatives of ys are taken as which in matrix form become dyl ..+. we find dl = Q -'y.. dy2 dz .144)for dl and d. (5.. in Eq.The coefficients a.137)can be written for the (n + 2) points 12" to z. (5.144a) where d l and d. (5. AY. = C Q .137)must be determined so that the boundary conditions are satisfied. dz . are the matrices of coefficients and Solving Eqs. = Qd. Eq.

151) and (5. It is possible to combine Eqs.149) The two-point boundq-value problem of Eq.1. . (5.328 Numerical Solution of Ordinary Differential Equations Chapter 5 where i J = = O.n + l (5. (5..106) can now be expressed in terms of the orthogonal collocation method as with the boundary conditions Eqs. .n + l 0. .151) and present them in matrix form: where . .152) constitute a set of ( 2 n + 4) simultaneous nonlinear equations whose solution can be obtained using Newton's method for nonlinear equations.l. ... (5.

. For this purpose. The above formulation of solution for a two-equation boundary-value problem can be extended to the solution of m simultaneous first-order ordinary differential equations.. (5. the same size as that of matrix A." 0 A . (5... . In the problem described above. .157) is defined by Eq.5. A Note that the matrix A in Eq. It should he noted that Eq.6 Nonlinear Ordinary Differential Equations-Boundary-Value Problems 329 The hold zeros in Eq. (5.148) and appears m times on the diagonal of the matrix A. . (5.. m. .154) are zero matrices of size ( n + 2) x ( n + 2).153) will not be used because the corresponding dependent values are determined by a boundary condition rather than by the collocation method. 2. . i i = 1. . . 0 0 . . The values of the dependent variables ( y .153) is solved for the unknown collocation points which means that we should exclude the equations corresponding to the boundary conditions. the first and the last equations in the set of equations (5. 0 = .. we define the following mahices: A. . . ..

160) at the time of solution. . . . If the problem to be solved is a second-order two-point boundary-value problem in the form with the boundary conditions ?(x.162) we may follow the similar approach as described above and approximate the function y(x) at (n + 2) points. .330 Numerical Solution of Ordinary Differential Equations Chapter 5 j = 0. as The derivatives of y are then taken as These equations can he written in matrix form: where .) = YO and ?(xf) = Y/ (5. n + 1) are then evaluated from the simultaneous solution of the following set of nonlinear equations plus boundary conditions: The equations corresponding to the boundary conditions have to be excluded from Eq. after transforming the independent variable from x to z. (5. 2.

are: Penicillinsynthesis: dy2 dt - 4% y2(0) = 0. The solution of the remaining n nonlinear equations can be obtained using Newton's method for nonlinear equations. In fact. are functions of temperature. = dimensionless concentration of cell mass y. (5. instead of the user choosing the collocation points. The parameters b. developed by Constantinides et a1. The equations that describe the state of the system in a batch penicillin fermentation. The choice of collocation points at the roots of the orthogonal polynomials reduces the error considerably. the adjoint variables.169) Eq.169) represents a set of (n + 2) simultaneous nonlinear equations.[6]. Apply the orthogonal collocation method to solve the two-point boundaryvalue problem arising from the application of the maximum principle of Pontryagin to a batch penicillin fermentation. 8: . Obtain the solution of this problem. A Y ) (5.5 Optimal Temperature Profile for Penicillin Fermentation 331 The two-point boundary-value problem of Eq. (5. Example 5.5: Solution of the Optimal Temperature Profile for Penicillin Fermentation. two of which correspond to the boundary conditions (the first and the last equation) and should be neglected when solving the set. and the optimal temperature.0 (2) where y.161) can now be expressed in terms of the orthogonal collocation method as BY = ~ ( z . = dimensionless concentration of penicillin t =dimensionless time. the method locates them automatically so that the best accuracy is achieved. and show the profiles of the state variables. Y .Example 5. 0 I r s 1. The orthogonal collocalion method is more accurate than either the finite difference method or the collocation method.

These parameter-temperature functions are inverted parabolas that reach their peak at 30°C forb. Apply the orthogonal collocation method to obtain the solution of this problem.005 w. = 20°C 8 =temperature.. t. The state and . "C. = 1. The inequality. Method of Solution: The fundamental numerical problem of optimal control theory is the solution of the two-point boundary-value problem.= 1. restricts the values of the parameters to the positive regime. at 25°C) w. The maximum principle has been applied to the above model to determine the optimal temperature profile (see Ref. the adjoint variables.94 (value of b. These functions have shapes typical of those encountered in microbial or enzyme-catalyzed reactions. which maximizes the concentration of penicillin at the final time of the fermentation. and show the profiles of the state variables.71 (value of b. [7]). and the optimal temperature. which invariably arises from the application of the maximum principle to determine optimal control profiles.1 (value of b . (1)-(6) form a two-point boundary-value problem.. = 0.yields the following additional equations: The adjoint equations: The necessary condition for maximum: Eqs. = 13. b. L 0 . (1) and (2). and b. The maximum principle algorithm when applied to the state equations. = 30°C w. The values of the parameters decrease by a factor of 2 over a 10°C change in temperature on either side of the peak. at 25°C) w. = 0.332 Numerical Solution of Ordinary Differential Equations Chapter 5 where w . at 20°C for b. at 25°C obtained from fitting the model to experimental data) w.

(6)] in terms of the system variables: The temperature 8 can be calculated from Eq.160) by Newton's method. z. variables and. the function keeps track of the equations to be solved. using the guessed initial conditions. The function continues with building the matrices Q.A.Example 5. Finally. (3.. (2). In the next section. therefore. followed by the final value equations. finally. The remaining three differential equations. This procedure is repeated until the convergence is reached at all the collocation points. correcting the dependent variables.5 Optimal Temperature Profile for Penicillin Fermentation 333 adjoint equations. if necessaty. Just before entering the Newton's technique iteration loop.m function must receive the values of the set of ordinary differential equations at each point in a column vector. where m = 3. and vectors Y and F. and also the number of equations should be equal to the total number of boundary conditions (initial and final). If these conditions are not met. by differentiating using forward finite differences method and. This procedure begins with evaluating the differential equations function values followed by calculating the Jacobian matrix. It is important to note that the co1location. the function builds the coefficients of the Lagrange polynomial and finds its roots.m is developed to solve a set of first-order ordinary differential equations in a boundary-value problem by the orthogonal collocation method. are solved by Eq. Therefore. and (4). C . The function applies Newton's method for solution of the set of nonlinear equations (5.160). in certain problems. The number of guessed initial conditions has to be equal to the number of final conditions. (8) once the system variables have been determined. Severalnumerical methods have been developedfor the solution of this class of problems.141). Eq. we express the necessary condition [Eq. It is also important to pass the . (1). the function gives a proper error message on the screen and stops execution. all the equations excluding those corresponding to the boundary conditions. It starts with checking the input arguments and assigning the default values. The vector of xj is then calculated from Eq. Program Description: The MATLAB function col1ocarion. when the necessary condition is not solvable explicitly for the control variable 8. A. which is independent of the other We first consider the second adjoint equation. that is. This difficulty is further complicated.160).. (5. coupled together through the necessary condition for optimality. The last part of the function is the solution of the set of equations (5. Eqs. with the initial value equations at the top. (5. constitute a set of simultaneous differential equations that are often unstable. may be integrated directly: This reduces the number of differential equations to be solved by one. the starting values for this technique are generated by the second-order Runge-Kutta method.

fname = input('\n M-file containing the set of differential equations : I . The program then calls the function collocation to solve the set of equations. penicillin concentration. (S). rho = input(' Relaxation factor = ' ) .0. The main program Example5-5. (11. and the temperature against time. optimal temperature profile. and adjoint variable of a batch penicillin fermentor. This program calculates and plots the concentration of cell mass. the program plots the calculated cell concentration.m evaluates the values of the set of Eqs. yf = input(' Vector of final conditions = ' I . and (4) at a given point. Knowing the system variables.30. guess = input(' Vector of guessed initial conditions = ' ) .fzero to calculate the temperature from Eq. It is important to note that the first input argument to Ex5-5func is the independent variable. Program ExampJe5-5. y l = collocation~fname. first adjoint variable.m asks the reader to input the parameters required for solution of the problem.le-6.rho. end % Plotting the results .m Solution to Example 5. YO = input(' Vector of known initial conditions = ' 1 .k).m % % % % % % Example5-5.y(:. This function also calls the MATLAB function.yf. fth=input(' M-file containing the necessary condition function n = input(' Number of internal collocation points = ' I . clear clc clf % Input data w = input(' Enter w " s as a vector : ' I . concentration of penicillin.[I. At the end.334 Numerical Solution of Ordinary Differential Equations Chapter 5 initial and final conditions to the function in the order corresponding to the order of equations appearing in the file that introduces the ordinary differential equations. The function Ex5-5func.0.l. the program calls the function fzern to find the temperature at each point.m. though it does not appear in the differential equations in this case.yO. It uses the function COLLOCATION to solve the set of system and adjoint equations. % Solution of the set of differential equations : . (Z).w.). [ t .w).guess. which is introduced in the function Ex5_5_theta.fth). % Temperature changes for k = 1:n+2 theta(k) = fzero(fth.5.n.

m function ftheta = Ex5-5-theta(theta. end b3 = w(5) * (l-w(2)*(theta-w(6))^2) / Il-w(2)*(25-~(6))"2). l e .2.plot(t.y(2.5. .fth) % Function Ex5-5-func.w. f = f'.w) % Function Ex5-5-theta.y(3.plot(t.plot(t.bl/bZ*y(1)^2. end b2 = w(4) * (1-w(Z)*(theta-w(3))Y) / 11-w(2)*(25-w(3))^2).b3. b3=0. end % Evaluating the function values £11) = bl*y(l) .M % This function calculates the value of the necessary condition % as a function of the temperature (theta). 0 . bl=0.5 Optimal Temperature Profile for Penicillin Fermentation subplot(2.Example 5. b2=le-6. It is used in solving % Example 5.3).y. if b1<0. y . % Temperature theta = f z e r o ( f t h .2). % Make it a column vector ExS_S_thefa.2.y(l. f (2) = b3*y(l). if b2<0.theta) xlabel('Time') ylabel('Temperature (deq C) ' ) title ( ' (d) ') ExS-5Jiunc.: ) I xlabel ( 'Time' ) ylabel('Penicil1in') title( ' (b)' ) subplot(2.5.4). 3 0 .2.6 .1). if b3<0. % Calculating the b's bl = w(1) * (1-w(Z)*(theta-w(3))Y) / (1-w(2)*(25-w(3)IA2).2.y.m function f = Ex5-5-func(t. : ) xlabel ( 'Time' ) ylabel ( 'Cell' ) title(' la) ' ) ) 335 subplot(2.M % This function introduces the set of ordinary differential % equations used in Example 5. :)) xlabel ( 'Time ') ylabel ( 'First Adjoint') title(' ( c ) ' ) subplot(2. plot(t. w ) . f (3) = -bl*y(3) + 2*bl/b2*y(l)*y(3) .

. . and GAMMA are the vectors of initial conditions. Pass an empty matrix for RHO or TOL to use the default value.yl = collocation(ODEfile. % % % % % % % % % % % % [X.N.TOL. are passed directly to the function F. end if nargin c 8 1 isempty(rh0) rho = 1.XF.YI=COLLOCATION('F'.P1.xO.GAMMA. Additional parameters P I .P2. % % % % % [X.~ ( 3 /) ) Il-w(2)*(25-~(3))~2): % The function £theta = ~(3)*(y(l)*dbl-y(1)^2*(dbl*b2-db2*bl) /b2^2)+y(l) *db3.XO..Yl=COLLOCATION('F'. Constantinides % January 1.n. . co1location. YO. .YF. ) uses relaxation factor RHO and tolerance TOL for convergence test..RHO.YO.YF.rho.yf. The equations are contained in the M-file F. 1999 if nargin < 7 1 isempty(n) n = 1. and starting guesses respectively. . tol.varargin) %COLLOCATION Solves a boundary value set of ordinary differential % equations by the orthogonal collocation method.NI integrates the set of ordinary differential equations from XO to XF by the Nth-degree orthogonal collocation method. The function returns the independent variable in the vector X and the set of dependent variables in the matrix Y. YF..x£. end % Initialization ..YO.M.guess. final conditions. See also SHOOTING (c) N.yO. end if nargin c 9 1 isempty(to1) to1 = le-6.m function [x. Mostoufi & A.336 Numerical Solution of Ordinary Differential Equations Chapter 5 % Calculating the b ' s bl = w(l) * (l-w(2)*(theta-w(3))^2) / (1-w(21*(25-w(3)lA21.XF.w ( 2 ) ) * 2 * ( t h e t a . dbl = w ( l ) * ( .GAMMA.XO. P 2 .

*(i-1).^i. . % Number of boundary conditions % Checking the number of equations ftest = feval(ODEfile. guess]. .')'.i+l) = i*x.Example 5.: ) = spline(p.') end r m length(y0).\n\n') % Coefficients of the Legendre polynomial f o r k = 0 : n/2 c1(2*k+l) = (-l)^k * gamma(2*n-2*k+l)/ .')'. % Collocation points ( z ) x = (xf-xO)*z/2+(xO+xf)/2. end end zl = roots (cl) . sort(z-1). % Number of initial conditions r + length(yf). % Building the matrix A Q I : .l). (2% * gamma(k+l) * gamma(n-k+l) * gamma(n-2*k+l)).[yO . % Collocation points (x) % Bulding the vector of starting values of the dependent variables [p. guess = (guess(:).5 Optimal Temperature Profile for Penicillin Fermentation yo = (yo(:). % Roots of the Legendre polynomial z = [-I.1) . C(:.xO.xO.x'). (xf-x0) /20.varargin{:)). for i = l:n+l Q :1 = x. C(:(1) = zeros (n+2. 2. guessl. if k < n/2 c1(2*k+2) = 0.q] = RK(ODEfile.xf. Please wait. : ) . % Make sure it's a column vector % 337 Make sure it's a column vector % Make sure it's a column vector % Checking the number of guesses if length(yf) -= length(guess1 error(' The number of guessed conditions is not equal to the number of final conditions. if length(ftest) -= m error(' The number of equations is not equal to the number of boundary conditions. . end y(r+l:m.') end = = fprintf('\n Integrating. .[yo for k = 1:m y(k.') '.11. end A = C*inv(Q). ~= ) ones(n+Z. yf = (yf(:).end)= yf (1:m-r).varargin{: )) . for k = l:m kl = (k-l)*(n+2)+1.q(k.

:). [position. for kkk = 1:n+2 . Am(kl:kZ. % Newton's method while max(abs(Y1 . end Y = Y'. y (k : nc2 : (m-1) * (n+2) +k). end fnk = A m * Y . 1). position = [ I . nc = (k-1) * (n+l) +kk: a(position(nc)) = Y (position(nc)) + dY(position(nc)).iter) Y1 = Y.01. f o r k = 1:m if k <= r position else position end end % Building the matrix Am % Building the vector Y % Make it a column vector % Collo~ationpoints excluding boundary conditions = = [position.x(k).kl:kZ)= A. F = zeros (m*(n+2) . else dY(position(k)) = 0.varargin(: ) ) . (k-1) *(n+2)+[2:n+2] I .F. 1): dY = zeros (m*(n+2). end end 8 Calculation of the Jacobian matrix for k = l:m for kk = l:n+l a = Y. Y(kl:k2) = y(k. Y1 = Y * 1. % Set dY for derivation for k = l:m*(n+l) if Y(position(k)) -= 0 dY(position(k)) = Y(position(k1) / 100. (k-1) * (n+2) + [l:n+ll I . maxiter = 100. Fa = zeros (m*(n+2). % Building the vector F for k = 1:n+2 ~ ( :k n+2 : (m-1) *(n+2)+k) = feval(ODEfile.1).1.Y)) > to1 & iter < maxiter iter = iter + 1. £print£(' Iteration %3d\n'.338 Numerical Solution of Ordinary Differential Equations Chapter 5 k2 = kl + n+l. iter = 0.

k2 = kl + n+l.03. position) = Y(position) + max(Iab~(dY(~osition)).9 Integrating. Please wait Iteration Iteration Iteration Iteration 1 2 3 4 . l.Fa: jacob(:.rho * inv(jacob1 * fnk(position). if iter >= maxiter disp('Warning : Maximum iterations reached. 201 known initial conditions = 10. end end % Next approximation of the roots if det(jacob) == 0 .. 0. 0.71. end % Rearranging the y ' s for k = 1:m kl = (k-l)*(n+2)+1.fnk(position1 / dy (position(nc) ) .') end Input and Results Enter w's Vector of Vector of Vector of as a vector : 113. feval(0DEfile.x(kkk).varargini:)): end fnka = Am * a .nc) = (fnka(positi0n) .94. : ) = Y(kl:k2)': end x = XI. else ~(~osition =) Y(position) .Example 5. 0 1 final conditions = 0 guessed initial conditions = 3 M-file containing the set of differential equations : 'Ex5-5-func' M-file containing the necessary condition function : 'Ex5-5-theta' Number of internal collocation points = 10 Relaxation factor = 0. 1.1.a~kkk:n+2:(m-l)*(n+2)+kkk). Y(k.5 Optimal Temperature Profile for Penicillin Fermentation 339 Fa(kkk : n+2 : (m-l)*(n+2)+kkki = .l*toll).005. 30.

. is an important factor in the convergence of the collocation method. The collocation method converged to the correct solution in i l iterations.5 Profiles of the system variables and the optimal control variable for penicillin fermentation. ::m $24 + 22 20 5 0 0. because it generates the starting values to the technique. Figs.5a to E5. E5.(O) = 3 was chosen as the guessed initial condition after some trial and error. The value of y.2 0. For this paiicular formulation of the penicillin fermentation.340 Iteration Iteration Iteration Iteration Iteration Iteration Iteration Numerical Solution of Ordinary Differential Equations 5 6 7 8 9 10 11 Chapter 5 Discussion of Results: The choice of the value of the missing initial condition for y. the maximum principle indicates that the optimal temperature profile varies from 30 to 20°C in the pattern shown in Fig.8 1 Figure E5.5d show the profiles of the system variables and the optimal control variable (temperature).5d.4 0 . E5. 6 Time 0.

at an escalating cost in the number of arithmetic operations to be performed. But because y.7 ERROR PROPAGATION. The nuncation error is a function of the number of terms that are retained in the approximation of the solution from the infinite series expansion. we concern ourselves with numerical stability considerations as they apply to the numerical integration of ordinary differential equations. The plethora of available numerical methods of integration of ordinary differential equations provides a choice of increasingly higher accuracy (lower truncation error). STABILITY.5. may grow in exponential or oscillatory pattern. Error propagation in numerical integration methods is a complex operation that depends on several factors. There are three types of errors present in the application of numerical integration methods. These are the truncation error. Fig. 5. The error has been magnified in order to illustrate it more clearly. as the initial point and calculates y. the roundoff error. creating the propagation error. Two types of stability considerations enter in the solution of ordinary differential equations: inherent stability (or instability) and numerical stability (or instability). On the other hand. which contains the truncation error for this step and a small roundoff error introduced by the computer. especially in numerical integration methods that march forward (or backward) for hundreds or thousands of steps. and with the concomitant accumulation of roundoff errors. The truncation and roundoff errors in numerical integration accumulate and propagate. The m c a t i o n error may be reduced by retaining a larger number of terms in the series or by reducing the step size of integration h. stability. even a very small roundoff error may affect the accuracy of the solution. Starting with a known initial condition yo. Computers carry numbers using a finite number of significant figures. and Convergence 341 5. AND CONVERGENCE Topics of paramount importance in the numerical integration of differential equations are the error propagation. Roundoff error. which contributes to propagation error. In this section. and the propagation error. each step being performed using rounded numbers. The behavior of error propagation depends on the values of the characteristic roots of the difference equations that yield the numerical solution. The truncation error is fixed by the . Roundoff errors may be reduced significantly by the use of double precision. in some cases. The next step starts with y. Stability. in addition to the new truncationand rouudoff errors from the second step. already contains truncation and roundoff errors. is entirely determined by the accuracy of the computer being used. the value obtained fory. Inherent stability is determined by the mathematical formulation of the problem and is dependent on the eigenvalues of the Jacobian matrix of the differential equations..7 Error Propagation. contains these errors propagated. thus causing the calculated solution to deviate drastically from the correct solution. and convergence of these solutions. The same process occurs in subsequent steps. which.the method calculates the value y.. numerical stability is a function of the error propagation in the numerical integration method. A roundoff error is introduced in the calculation when the computer rounds up or down (or just chops) the number to n significant figures. However.6 illustrates the propagation of error in the Eulerintegration method.

7. Some techniques work well with one class of differential equations but fail with others. choice of method being applied.342 Numerical Solution o f Ordinary Differential Equations Chapter 5 Xo X~ ji3 Figure 5.1 Stability and Error Propagation of Euler Methods Let us consider the initial-value differential equation in the linear form: where the initial condition is given as Y(~o= ) Yo (5.172) . we examine systematically the error propagation and stability of several numerical integration methods and suggest ways of reducing these errors by the appropriate choice of step size and integration algorithm. The analytical solution of this differential equation is Y(X) = yOeAx (5. by the step size of integration.171) We assume that h is real and yo is finite.6 Error propagation of the Euler method. it is necessary to examine the error propagation and stability of each method individually and in connection with the differential equations to be integrated. In the sections that follow. 5. and by the values of the derivatives of the functions being integrated. For these reasons.

we obtain the recurrence equation Yn. Under these conditions: lim y(x) r-= 0 (5.173) Next. Momentarily we ignore the lmncation and roundoff errors.60).175) Using the methods described in Sec. Applying Eq..178) The constant C is calculated from the initial condition.182) Because (1 + h i ) is the root of the characteristic equation (5.5.183) . 2 . + hay..6.177) From this. n can increase without bound.(1 + h h ) ~ .170) using the explicit Euler method is absolutely stable if I1 + hAl s 1 (5. A numerical solution is said to be absolutely stable if lim yn n-= 0 (5. the final form of the solution is problem.= 0 (5..7 Error Propagation.: Therefore...its behavior is determined by the value of (1 + hi).176).181) The solution of the differential equation (5. at x = x. 3.175) as y. k (5. The differential equation is an in~tial-value Because the solution yn is a function of (1 + hi)".174) homogeneous difference equation which rearranges to the followingj5fir~t-order Y . (5. and Convergence 343 This solution is inherently stable for h < 0. we obtain the solution of the difference equation (5. an alternative definition of absolute stability is lpilsl i = 1 . Stability. we obtain the characteristic equation whose root is p1 = 1 + hh) (5. = C(l + hi)" (5. therefore. (5.. we examine the stability of the numerical solution of this problem obtained from using the explicit Euler method.l = Y.

182) is rearranged to This inequality sets the limits of the integration step size for a stable solution as follows: Because h is positive. In the earlier discussion of the stability of difference equations (Sec. we mentioned that a solution is stable. the inequality (5. 3.51 - 1 J 0. 2.5 - 32. and for this reason. At the outset of our discussion. 4.185) is a finite general stability boundary. we assumed that A was real in order to simplify the derivation. Returning to the problem at hand. and 5. when complex roots are present. Any method with an infinite general stability boundary can be called unconditionally stable.344 Numerical Solution of Ordinary Differential Equations Chapter 5 where more than one root exists in the multistep numerical methods.5 2 - unstable r E - 21. converging with damped oscillations. then h < 0 and Inequality (5.6). and the moduli of the roots are less than or equal to unity: 4- 3. This assumption is not necessary: h can be a complex number. . 3.5 0 -6 -5 4 -3 Re(hh) -2 -1 0 1 Figure 5.7 Stability region in the complex plane for Runge-Kutta methods of order 1 (explicit Euler). the explicit Euler method is called conditionally stahle.

We also write the calculated value where TE. n + ~ (5.28) We define the accumulated error of the numerical solution at step (n + I) as where y (x. (5.186) describe the circle with a radius of unity on the complex plane shown inFig. + (5..+. .. showing as many terms as needed for the Euler method: + + .?(xn) + hlf(x. is the roundoff error introduced by the computer in step (n + 1) where RE.i . the corresponding curve in this figure is marked by RK1.f ( x n .187)-(5.. which describes the propagation of the error in the numerical solution. We now return to the consideration of the truncation and roundoff errors of the Euler method and develop a difference equation.7. .191) to . (5. Y.. ?(x.170) using the Euler integration method. We work with the nonlinear form of the initial-value problem where the initial condition is give11by ?(xo) = Yo (5.))I . obtained from the implicit Euler formula + ..) as aTaylor series expansion. Y.184) and (5.189) we have = Y.) is the exact value of y..) .190) which simplifies to En+.. Since the explicit Euler method can be categorized as a firstorder Runge-Kutta method.f ( x ."+. and Convergence 345 The two inequalities (5. = En + hlf(x.?(xn))I - T~. We then write the exact solution y(x.. y.n+l + R ~ .) . Stability.191) The mean-value theorem can be used to further modify the error equation (5. is the local truncation error for step (n + 1). Combining Eqs.5. .. and yn is the calculated value of y at x.TE. The set of values of hh inside the circle yields stahle numerical solutions of Eq.7 Error Propagation.+. 5.

= TE= constant RE. l = - hh for I1 hhl < 1 (5. However. The truncation and roundoff error terms in Eq. E. (5. = 0.+. As expected. and the eigenvalue of the differential equation. which can be solved only by iteration.197) A great deal of insight can be gained by thoroughly examining Eq.175) and (5. = R E= constant TE + (5.h < 0. (5. .195) introduce the particular solution. Under this assumption..198)]. the error is bounded. (5. the value of ( 1 + hh) is the determining factor in the behavior of the propagation error. are identical. . is calculated by assuming that the initial condition of the differential equation has no error.195) reveals that the characteristic equations for the solution y. T E = + RE "-n-- lim l ~ . The constant C . Consider first the case of a fixed finite step size h.198) (5.194) Eq. Eq. (5. (5. (5.197). with the number of integration steps increasing to a very large n.199) for I1 + hhl > 1 In the first situation [Eq. The final form of the equation that describes the behavior of the propagation error is En = T E hh +R~[(+ l hh)" - 1. and the error E .346 Numerical Solution of Ordinary Differential Equations Chapter 5 This is afirst-order nonhomogeneous difference equation with varying coefficientr.27) becomes identical to Eq. (5. that is. the roundoff error. by making the following simplifying assumptions: . The numerical solution differs from the exact solution by only the finite quantity (-T. which is afunction of the truncation error. +RJ/hh. 0 < h < Zllhl. The limit on the error as n m is + lim I E . the step size. and the numerical solution is stable.193) simplifies to whose solution is given by the sum of the homogeneous and particular solutions 181: Comparison of Eqs.170). (5.

203) However. So we conclude that for inherently stable differential equations. (5. the absolute propagation error is the pertinent criterion for numerical stability. however. For this reason we introduce the concept of relative error defined as relative error - t 2 Y. we obtain the relative error as The relative error is bounded for h > 0 and unbounded for h < 0. the error is unbounded and the numerical solution is unstable. the Enler method.197). For h > 0. (5. . are convergent because lim T. whereas for inherently unstable differential equations. h-0 = 0 (5. the exact solution is inherently unstable. roundoff error is never absent in numerical calculations.206) This is the "catch 22" of numerical methods: A smaller step size of integration reduces the truncation error but requires a large number of steps. h > 0.5. Stability. This. and Convergence 347 In the second situation [Eq. 0 i x i a. and most other integration methods.7 Error Propagation. Utilizing Eqs.lim h-0 ( 1 + hh)" hh - 1 Application of L'Hdpital's rule shows that the roundoff error propagates unbounded as the number of integration steps becomes very large: lim tn = RE[-] h-n (5. of course. A.1 h-0 = - R. A numerical method is said to be convergent if - lim I tnl = 0 h-0 (5.199)1. so that and we increase the number of integration steps to a very large n.203) In the absence of roundoff error.180) and (5. > 0. Let us now consider a fixed interval of integration. causes h 0. thereby increasing the roundoff error. the relative propagation error must be investigated.204) and lim lenl h-0 = 0 (5. Ash 0 the roundoff error is the crucial factor in the propagation of error: lim 1e.

the following inequality must be true for a stable solution: I1 . for the solution and the propagation error -T.3). 5.7.21 1) This imposes the limit on the step size: -2 5 hhs 0 (5.2 Stability and Error Propagation of Runge-Kutta Methods Using methods parallel to those of the previous section. the implicit Euler method is unconditionally stable for h < 0.170). I . En+. > 0.- = 0 and the error is bounded: lim a-- = - T E + RE ha (1 - Ah) No limitation is placed on the step size. therefore.hhi < 1 (5.348 Numerical Solution of Ordinary Differential Equations Chapter 5 A similar analysis of the implicit Euler method (backward Euler) results in the following two equations. = + RE (1 . On the other hand. when .212) It can be concluded that the implicit Euler method has a wider range of stability than the explicit Euler method (see Table 5. these are: Second-order Runge-Kutta: .ha) hh [(I ' h h y 1 For h < 0 and 0 < h < m. the solution is stable: lim yn " . For the differential equation (5. the recurrence equations and the corresponding roots for the Runge-Kutta methods can be derived [9].

0 r.5. and Convergence 349 Third-order Runge-Kutta: Table 5. -0.785 -5.7 i 1 hh i 0 hh 1 . 0 -2.7 Error Propagation.hh 0 . Stability.5 s hh s 0 -2.546 I.3 Real stability boundaries Method Boundary Explicit Euler 2 1 hA 1 0 Implicit Euler Modified Euler (predictor-corrector) Second-order Runge-Kutta Third-order Runge-Kutta Fourth-order Runge-Kutta Fifth-order Runge-Kutta Adams -2 I- hh r.

The condition for absolute stability: applies to all the above methods.170). 5. and the regions of stability in the complex plane are shown on Fig. The absolute real stability boundaries for these methods are listed in Table 5. For the differential equation (5. the recurrence equations and the corresponding roots for the modified Euler.2 and varies for different fifth-order formulas.7. which appears in Tahle 5.3 Stability and Error Propagation of Multistep Methods Using methods parallel to those of the previous section.3.219) and (5. and Adams-Moulton methods can he derived [9]. as the order increases.350 Numerical Solution of Ordinary Differential Equations Chapter 5 Fifth-order Runge-Kutta: The last term in the right-hand side of Eqs. these are: Modified Euler (combination of predictor and corrector): Adams: . (5. In general. so do the stability limits.7. Adams. 5.220) is specific to the fifth-order Runge-Kutta.

5. 2 . .8. Adams.. lpil I 1 i = 1 .3. Figure 5.8 Step Size Control 351 Adams-Moulton (combination of predictor and corrector): The condition for absolute stability.8 Stability region in the complex plane for the modified Euler (Euler predictor-corrector).183) applies to all the above methods. 5..k (5. The absolute real stability boundaries for these methods are also listed inTable 5. and Adams-Moulton methods.. and the regions of stability in the complex plane are shown on Fig..

For problems in which computation time becomes excessive. In Sec. and it should be shortened in order to achieve an acceptable truncation error.170). which provides the estimation of the local truncation error. will guarantee stability at the expense of computation time. Otherwise. 5. the optimum number of application of corrector is two.352 Numerical Solution of Ordinary Differential Equations Chapter 5 The discussion of stability analysis in the previous sections made the simplifying assumption that the value of h remains constant throughout the integration. if the convergence is achieved before the second corrected value. if the convergence is not achieved after the second application of the corrector. a larger than acceptable difference between the two calculated y values suggests that the step size is large. On the other hand. the step size should be reduced. A simple test for chccking the step size is to do the calculations at each interval twice: Once with the full step size. and let the program automatically change the step size at each point until the desired accuracy is achieved. we showed that the stability of the numerical solution of differential equations depends on the value of hh. however.2). In the case of the linear differential equation . the difference between the predicted value of y by both approaches is less than the specified convergence criterion. A good example of such an approach is the Runge-Kutta-Fehlherg method (see Table 5. This error estimate can be easily introduced into the computer program.7. the step size may be increased. The step size of integration must be chosen using the maximum possible value of h. Another method of controlling the step size is to obtain an estimation of the truncation error at each interval. and that h together with the stability boundary of the method determine the step size of integration. in the case of using a predictor-corrector method. If at the end of the interval. Therefore. (5. and then repeat the calculations over the same interval with a smaller step size. This is true for linear equations such as Eq. of course. usually half that of the first one.27). the step size may be increased. thus resulting in the minimum step size. the value of h may vary considerably over the interval of integration. This. it is possible to develop strategies for automatically adjusting the step size at each step of the integration. for the nonlinear equation (5. As mentioned before.

5. . . However.2. the equations are said to be stiff.1921. The stifiess ratio (SR) of such a set is defined as .I i = 1.9 Stiff Differential Equations 353 h is the eigenvalue of that equation. The step size of integration is determined by the stability boundary of the method and the maximum eigenvalue. and it remains a constant throughout the integration. . . when the maximum eigenvalue is several orders of magnitude larger than the minimum eigenvalue. no unusual problems arise in the integration of the set. This analysis can be extended to a set of simultaneous nonlinear differential equations: Linearization of the set produces the Jacobian matrix The eigenvalues { h . n ) of the Jacobian matrix are the determining factors in the stability analysis of the numerical solution. so that h can be obtained from the partial derivative of the function with respect toy: The value of h is no longer a constant but varies in magnitude at each step of the integration. The nonlinear differential equation can be linearized at each step using the mean-value theorem (5. When the eigenvalues of the Jacobian matrix of the differential equations are all of the same order of magnitude.

1). (5.1 Derive the second-order Runge-Kutta method of Eq.)I 1rirn The step size of integration is determined by the largest eigenvalue.2 The solution of the following second-order linear ordinary differential equation should be determined using numerical techniques: The initial conditions for this equation are. (b) Find the solution using eigenvalues and eigenvectors.0. and k. 5. therefore. min iReal(lZ.C where k. PROBLEMS 5. The MATLAB functions ode23s and odel5s are solvers suitable for solution of stiff ordinary differential equations (see Table 5.3 A radioactive material (A) decomposes according to the series reaction: kl k2 A + B . and evaluate the variables in the range 0 i t i 1. The rate equations are .92) using central differences. at t = 0: (a) Transform the above differential equation into a set of first-order linear differential equations with appropriate initial conditions. integration of differential equations using explicit methods may be time intensive. (c) Use the fourth-order Runge-Kutta method to verify the results of part (b). and the final time of integration is usually fixed by the smallest eigenvalue. respectively. Finlayson [I] recommends using implicit methods for integrating stiff differential equations in order to reduce computation time. are the rate constants and B and C are the intermediate and final products.354 Numerical Solution of Ordinary Differential Equations Chapter 5 SR = 1"'" max IReal(h)l . 5..

@) At time r =1 s and t = 10 a. In addition. the rate of production of penicillin has been mathematically quantified by the equation Penicillin (y.. a penicillin-producing organism [61. This equation is a modification of the logarithmic law The tern1 (1 . B. C.Problems 355 where C. what are the concentrations of A .5 In the study of fermentation kinetics.4 (a) Integrate the following differential equations: for the time period 0 i t I 5 . (2) the fourth-order Runge-Kutta method. . .y. C. using ( I ) the Euler predictor-corrector method. 5.. The values of the rate constants are Initial conditions are . respectively. the logistic law has been used frequently to describe the dynamics of cell growth. (b) Which method would give a solution closer to the analytical solution? (c) Why do these methods give different results? 5. (a) Use the eigenvalue-eigenvector method to determine the concenttations C as a funcuon of tlme t. and C . and C .. and C. which is proportional to the concentration of the penicillin itself. The logistic law has been used successfully in modeling the growth of penicillium chryscogenum. and C? (c) Sketch the concentration profiles for A.) is produced at arate proportional to the concentration of the cell (JJ.) in the logistic law accounts for cessation of growth due to a limiting nutrient.)andis degraded by hydrolysis. 6. B. and C.lk. are the concentration7 of materials A.

y. (b) Show that k. In turn. the gluconolactone hydrolyzes to [ o m the gluconic acid. This model. present in the microorganism.(O) the range of r is 0 r i 212 h. The enzyme glucose oxidase.6 The conversion of glucose to gluconic acid is a simple oxidation of the aldehyde group of the sugar to a carboxyl group. The overall mechanism of the fermentation process that performs this transformation can be described as follows: Cell growth: Glucose Glucose oxidation: Glucose+02 Gluconolactone hydrolysis: Gluconolactone+HZO Peroxide decomposition: H2°2 Catalyst G1ucoseOxidase . has been developed by Rai and Constantinides [lo]. which produces gluconic acid. and y.0. converts glucose to gluconolacrone. Gluconolactone+H202 + Cells 4 Cells - Gluconic acid .374 k. This transformation can be achieved by a microorganism in a fermentation process. k.03120 k. is equivalent to the maximum cell concentration that can be reached under given conditions. which describes the dynamics of the logarithmic growth phases. = 0. H20+-0 1 2 2 A mathematical model of the fermentation of the bacterium Pseudomonas ovalis. = 47.(O) = 5. = 3.356 Numerical Solution o f Ordinary Differential E q u a t i o n s Chapter 5 (a) Discuss other possible interpretations of the logistic law. 5.70 = 0.01268 i at t = 0. Use the following constants and initial conditions: k . can be summarized as follows: Rate of cell growth: I Rate of gluconolactone formation: .0. (c) Apply the founh-order Runge-Kutta integration method to find the numerical solution of the cell and pcnicillin equations. = 0.

N.51 b. these equations take the general form where N. y . The Lotka-Volterra equations have also been formulated for such .= 3.7 The best-known mathematical representation of population dynamics between interacting species is the Lokta-Volterra model [I I]. to y. For the case of two competing species. for the period 0 i r s 9 h.. = concentration of glucononctone y. = 18. develop the time profiles of all variables. and the predators depend on the prey for their entire supply of food. the values of the five parameters were determined from experimental data to he h.-b.= 37. which is a herbivore. These two animals coinhahit a region where the prey have an abundant supply of natural vegetation for food. The initial conditions at the start of this period are 5.6. The functions f . is the population density of species I and N. acarnivore. The predator-prey problem.Problems Rate of gluconic acid formation: 357 Rate of glucose consumption: where y. = concentration of glucose h. = 0. and a set of constants whose values depend on natural birth and death rates and on the interactions between the two species. =concentration of cell y. Numerous examples of such interactions can be citedfrom ecological and microbiological studies. these functions can be expressed in terms of N. presents a very interesting ecological example of population dynamics.. that is.949 b. Let us now consider in detail the classical predator-prey problem. On the other hand. describe the specific growth rates of the two populations.169 At these conditions. = 1.is the population density of species 2. the interaction between two wild-life species. and the predator. and where predators usually feed on a variety of prey.72 h. which has been studied extensively.. the interaction between bacteria and phages in a fermentor is a well-known nemesis to industrial microbiologists. This is a simplification of the real ecological system where more than two species coexist.439 h. the prey. and f. =parameters of the system which are functions of temperature and pH At the operating conditions of 30°C and pH 6. = concentration of gluconic acid y. Under celtain assumptions.

d = a - N.dt Y (d) In the presence of the prey. the birth rate is higher than the death rate.dr (h) In the presence of the predator the prey is consumed at a rate proportional to the number of predators present PN. P. The park comprises a single large island and many small islands which extend off the main island.: (c) In the absence of the prey. According to a very interesting aticle in Nutional Geographic [12]. probably swimming in from Canada. that is.7aI. y. the longest study of its kind [13]-[15] still seeks to define the complete cycle in the ebb and flow of predator and prey populations. we make the following assumptions: (a) In the absence of the predator.358 Numerical Solution of Ordinary Differential Equations Chapter 5 complex systems. our ecological system will contain only twointeracting species. Under these circumstances. This is a set of simultaneous first-order nonlinear ordinary differential equations. as the inevitable consequence of such a situation is the starvation of the predator: dN2 - N. the specific growth rate of the predator is The equations in parts (b) and (d) constitute the Lokta-Voltema model for the one-predator-oneprey problem. ravaging vegetation. therefore. and 6. dNl h . Anexcellent exampleof such anecological systemisIsleRoyaleNational Park. The solution of these eqnationsfirst requires the determination of the constants a. their unchecked numbers approached 3000. Since 1958. . the predator has an ample supply of food. came a predator-the wolf. moose arrived on Isle Royale around 1900. and assuming that no catastrophic diseases plague the prey. Bccause an abundant supply of natural vegetation for food is available. the predator has a negative specific growth rate (-y). with wolves tluctuatingfrom 11 to 50 and moosefrom 500 to 2400 [seeTable P5. however. 6 N . the net specific growth rate a is positive. which enables it to survive and produce at a rate proportional to the abundance of the prey. across an ice bridge from Ontario. and the specification . Rearranging these two equations to put them in the canonical form. for the sake of this problem. the prey has a natural birth rate b and a natural death rated. In 1949. a 210-square mile archipelago in Lake Superior. In order to formulate the predator-prey problem. By 1930.

However. it is more customary to specify initial population densities.(t. we will specify the initial population densities of the prey and predator to be N. The latter could be either initial or final conditions. In this problem. it is conceivable that one may want to specify final values of the population densities to be accomplished as targets in a well-managed ecological system.7a Population of moose and wolves on Isle Royale Year Moose Wolves Year Moose Wolves 359 of boundary conditions. because actual numerical values of the population densities may be known at some point in time. which can be called the initial starting time.) = NP and N2(tO)= N: (3) .Problems Table P5. In population dynamics.

( I ) and (2) to zero: and rearranging these equations to obtain the values of N. . Vandermeer [I 61 examined the stability of the solutions of these equations around equilibrium points. and N. (1) and (2). 2): . to highly unstable situations. Several references on this topic are given at the end of this chapter. damped oscillations." The stability is determined by examining the eigenvalues of the Jacobian matrix evaluated at equilibrium: wheref. Different assumptions would yield another set of differential equations [see Problem (5. The eigenvalues of the Jacobian matrix can be obtained by the solution of the following equation (as described in Chap. . In addition.8)]. In a recent treatise on this subject. The literature on the solution of the Lotka-Volterra problems is voluminous. the stability of these equations must be examined thoroughly. The equations must be integrated numerically using any of the numerical integration methods covered in this chapter.'. The neighborhood stability analysis is undertaken in the neighborhood of a single equilibrium point. the solution patterns may vary from stable. .360 Numerical Solution of Ordinary Differential E q u a t i o n s Chapter 5 Equations (1)-(3) constitute the complete mathematical formulation of the predator-prey problem based on assumptions (a) to (d). N2') will satisfy the equilibrium equations. multiple points will satisfy the equilibrium equations. andf. At other times. are the right-hand sides of Eqs. where the species reach their respective stable symbiotic population densities. These points are located by setting the derivatives in Eqs. Vandermeer stated that: "Sometimes only one point (N. the choice of constants and initial conditions influence the solution of the differential equations and generate a diverse set of qualitative behavior patterns for the two populations. before numerical integration is attempted. Depending on the form of the differential equations and the values of the constants chosen. in which one of the species is driven to extinction while the other explodes to extreme population density. at the equilibrium point in terns of the constants where * denotes the equilibrium values of the population densities. respectively. However. A closed-form analytical solution of this system of nonlinear ordinary differential equations is not possible.

we estimate the period of oscillation to be 25 years. saddle point Stable. From these data. Table P5. oscillatory Unstable. These possibilities are summarized in Table P5. For this reason.Problems 361 For the problem of two differential equations. b.. 4 Zero Zero Zero Nonzero Nonzero Nonzero Stability analysis Stable. a. n..76.76 a.) and imaginary parts ( h . This was based on the moose data. a. (1) and (2). In order to obtain a realistic solution to these equations. oscillatory Neutrally stable. which cover the period 1 9 5 9 1998. one negative Negative Positive Zero Many combinations of values of constants and initial conditions exist that would generate solutions to Eqs. . oscillatory Negative Positive One positive.) detennine the nature of the stability (or instability) in the neighborhood of the equilibrium points. the wolf data show a shorter period. These eigenvalues take the general form where i = The values of the real parts (a. nonoscillatory Unstable. there are two eigenvalues that can possibly have both real and imaginiuy parts. 4. we predict that the predator equation may not be a good representation of the data.7a. nonoscillatory Metastable. we estimate the average values of the moose and wolf populations (over the entire 40-year period) and use these as equilibrium values: In addition. Lotka has shown that the period of oscillation around the equilibrium point is approximated by . we utilize the data of Allen 1131 and Peterson [14] on the moose-wolf populations of Isle Royale National Park given in Table P5.

versus N. Choose the constants and initial conditions of your equations carefully in order toobtain an ecologically feasible situation. the complete set of constants is This initial conditions are taken from Allen 1131for 1959. For example. account for at least one additional source of food for the predator (a second prey).(1959) = 20 Integrate the predator-prey equations for the period 19591999 using the above constants and initial conditions and compare the simulation with the actual data. This term can be viewed as either a contribution to the death rate or a reduction of the birth rate caused by overcrowding of the species. draw phase plots ofN. Draw the phase plot of N. the real parts of the eigenvalues of thelacobian matrix are zero.8 It can be shown that whenever theLotka-Voltenaproblem hastheformofEqs. In addition. By assuming the value of a to be 0. or attempt to quantify other interferences you believe are important in the life cycle of these two species.7. the earliest date for which complete data are available. 5. This implies that the solution always has neutrally stable oscillatory behavior.3 (this is an estimate of the net specific growth rate of the prey in the absence of the predator). Integrate the resulting equations and obtain the time profiles of the populations of all the species involved.(1959) = 522 and N... These are N. In this problem. versus N. and so on. 5. and discuss the stability of these equations with the aid of the phase plot. and discuss the stability considerations with the aid of the phase plots.7 did not include the crowding effect each population may have on its own fertility or mortality.362 Numerical Solution of Ordinary Differential Equations Chapter 5 These three equations have four unknowns. This is explained by the fact that assumptions (a) to (d) of Prob.9 The steady-state simulation of continuous contact countercurrent processes involving simultaneous heat and mass transfer may be described as a nonlinearhoundary-value problem [3]. 5. Eq. (1) can be rewritten with the additional term EN. modify the Lotka-Volterra equations by introducing the effect of overcrowding.': The new term introduces a negative density-dependency of the specific growth rate of the prey on its own population.. N. for a continuous adiabatic gas absorptioncontactor unit. 5.For instance. versusN. the model can be written in the following form: . (1) and(2) inProh.

10 A plug-flow reactor is to be designed to produce the product D from A according to the following reaction: A .11 I0 r d 6" = = 1. TJ0) = 298 xA(l) = 0. Value ofA is 5 $lmol A.D r.Problems 363 Thermodynamic and physical property data for the system ammonia-air-water are J.O03CA T" = mole U l L.36~10" N/m2 4.1 molls enters the reactor.(O) ( I = = 0.41 = = CL C. = 1. the following undesired reaction also takes place: A . = 60CA mole D I L. AB G H N = J.U 0.212x103 K 5.0 Calculate the profiles of all dependent variables using the shooting method 5.5 Lls and molar flow rate of 0. 2 3 ~ 1 0 N ' ~l m Z = p = 0.003x103 K 1.08x10SJ I kmol 1. .05 TL(l) = 293 Y.36x105J/kmol 232 Jlkmol 93 J I kmol 10S~/m2 A. The undesired product Uis a pollutant and it costs 10 %lmolU to dispose it.0 J l m o l = 1. s In the operating condition of this reactor. whereas the desired product D has a value of 35 $/mol D. What size of reactor should be chosen in order to obtain an effluent stream at its maximum value? Pure reactant A with volumetric flow rate of 1. s 1 + 1O5C.0 1 . = 6 . P = = = The inlet conditions are YA(0) = 0.

McGraw-Hill. 132.... Prentice Hall.mlSolurions o f Boundqv V ~ ~ l u Problems e for Ordinav Differrnricrl Equations. Prentlcc Hall. 16. 1 I. S. 1975.. J. vol.. N~rmer.). Fogler. 3rd ed. C. Tire Wolves "flsle Royale. R. 2. Lotka. vol.. vol. E1etnenr. WI. Willow Creek Press. E. R.364 REFERENCES Numerical Solution of Ordinary Differential E q u a t i o n s Chapter 5 1. 1975. 1970.. "Mathematical Modeling and Optimization of the Gluconic Acid Fermentation. p. 1 . 167. B. Allen. Lapidus.. K. Annual Reports. O. Spencer. L. V. L. . 1081. p. 1998. Development of Mathematical Models for Batch Penicillin Fermentations. 12. Nonlinear Analysis in Chemical Engineering. 1956. 7. R. R. McGraw-Hill.. New York. Ecologicnl Srudies of Wolver on Irle R q a l e . April 1985. 12. and Chhabra. 1999. Houghton Mifflin. Minocqua.. of Nonlinear Bounduq' Valxe Problems wuh 3. 534.. (ed.."Bior~ch.. Peterson. M1. P. Peterson. Constantinides. De Kee. Numerical S~~lurion Applicarlonr.. Rai. L. Constantinides. 12. P. vol. Ncw York. "Optimization of Batch Fermentation Processes. Hanser. Academic. Lapidus.s of Mrr~l~emotical Biolop. Rheology of Pol~vnerir Systems: Principles atid Applicnrions. I. 1962. Optimum TemperatureProfilesfor Batch PenicillinFermentations.. no. I . 1971." Narional Geographic.. 15. 1970. A. D. I. New York.. Woh~es (fMinong. 11. 1981 .. 13. 1 9 8 4 1998. J. of Chemical Reacrion Enginrrring. New York. Elemrntav Mathemaricaf Ecologs. 0.md Constantinides. Wiley. L. p. 9. Upper Saddle River. J. 803. New York. "Isle Royale: A North Woods Park Primeval. H. 8. Boston. Germany.. 114." A I C I I E S ? ~ ~ Ser. and Hlavifek. L. 1973. Vandermeer. and Gaden. and Gaden. D.. Aziz. J.for Chemical Engineering. Munich. Kubifek.. L. Eiem~nlr NJ.. 69.. 1995. "Optimization of Batch Fermentation Processes. Carreeu.. 1973 14. N~#merical New Ynrk. Bioen~. Solution qf Orrlinar? Differenli Equations. L.. 1980. Jr. Jr. A Broken Bnlrrnce.. M. Houghton. Michigan Technological University. H.. Academic. Bioeng. E. 6. L. I." Rioferh. Elliot. Finlayson. New York.. and Sienfeld. Digital Computalion. A. 5. A. 10. Spencer. lnc. Dover. A. A... 4. R. A. V. p.

- Ecuaciones Parciales
- Administración de Operaciones - 8va Edición - Krajewski, Ritzman & Malhotra - FL
- El Análisis del Ciclo de Vida y la Gestión Ambiental
- Desarrollo Sostenible
- Análisis Numérico - 7ma Edición - Richard L. Burden & J. Douglas Faires
- Matlab Para Algebra Lineal
- Ecuaciones Lineales y Matrices
- dinamicadeestructurasconmatlab-130205004741-phpapp01
- Tutorial Excel VBA 2010
- 1_numerical Methods for Chemical Engineers With Matlab Applications_1
- Tutorial Excel VBA 2010
- 6_numerical Methods for Chemical Engineers With Matlab Applications
- 5_numerical Methods for Chemical Engineers With Matlab Applications
- 3_umerical Methods for Chemical Engineers With Matlab Applications
- 2_numerical Methods for Chemical Engineers With Matlab Applications
- 1_numerical Methods for Chemical Engineers With Matlab Applications_1
- Micro Econom Iacon Excel
- Micro Econom Iacon Excel
- Matlab en 5 Lecciones de Numerico
- Curso Introductorio Sobre Matlab y Simulink_excelente
- Curso Introductorio Sobre Matlab y Simulink_excelente
- Simulink Tutorial Completo
- Tutorial Simulink 3
- Utilizacion Practica de Matlab

Sign up to vote on this title

UsefulNot useful- 54018020 Numerical Methods for Chemical Engineers With MATLAB Applicationsby Gaurav Subedi
- Chemical Thermodynamics for Process Simulation [urgen Gmehling, Barbel Kolbe,Michael Kleiber and Iurgen Rarey.pdfby ahmadomar521
- Chapter 6 - Differential Equationsby diktatorimhotep8800
- EMⅠ 10 13 Bernoulliby Dhany SSat

- 54018020 Numerical Methods for Chemical Engineers With MATLAB Applications
- Chemical Thermodynamics for Process Simulation [urgen Gmehling, Barbel Kolbe,Michael Kleiber and Iurgen Rarey.pdf
- Chapter 6 - Differential Equations
- EMⅠ 10 13 Bernoulli
- 169 Nu Ran
- Linear-Presentation on 1st+2nd chapter
- Diff Eqns
- Differential Equations for Engineering Science 2014 by Serdar Yüksel
- Crivelli the Stormer Verlet Method
- Mws Gen Ode Txt Runge2nd
- Math 237 Lecture Notes
- Differential Equation
- Exam 1, Spring 2011 -- Solutions.pdf
- Notes Lecture 2
- Minggu 2 1 Engineering Mathematics Differential Equations
- Ode
- Existance Theory for First Order Nonlinear Random Dfferential Equartion
- Analysis of Numerical Differential Equations and Finite Element Method - J. Brandenburg, L. Clemmons (College Publ., 2012) WW.pdf
- p09
- Ch_99-AppdxH
- complex
- Examples of Differential Equations - Wikipedia, The Free Encyclopedia
- Theta
- Ode
- Topic 2 Part 2 - Solutions to 2nd Order ODEs Students
- diffeq 1
- Differential Equations
- Runge Kutta Method. 1
- Math EE Draft
- Project 3
- 4_umerical Methods for Chemical Engineers With Matlab Applications