10
218 EXCEL NUMERICAL METHODS and although writing the differential equation, such as the above, may be simple, solving the problem is not. By "solving," we mean that we want to be able to calculate the value of y for any value of x. Some differential equations, such as 10-1, are solvable by symbolic integration (the integrated equation is In y = -kt + const), but many others may not be amenable to solution by the "pencil-and- paper" approach. Numerical methods, however, can always be employed to find the value of the function at various values o f t . Although we haven't found an expression for the function F(x, y), but simply obtained a table of y values as a function of x, the process is often referred to as "integration." You may remember from your freshman calculus class that when an expression is integrated, an arbitrary constant of integration is always part of the solution. For example, when equation 10- 1 is integrated, the result is In y = -kt + In yo, or yt = yoe-". A similar situation pertains when numerical methods are employed: to solve the problem, one or more values of the dependent variable and/or its derivative must be known at specific values of the independent variable. If these are given at the zero value of the independent variable, the problem is said to be an initial-value problem; if they are given at some other values of the independent variable, the problem is a boundary-value problem. This chapter deals with initial-value problems, while the following chapter deals with boundary-value problems. Solving a Single First-Order Differential Equation This section describes methods for solving first-order differential equations with initial conditions (the order of a differential equation is determined by the order of the highest derivative in the equation). Two methods will be described: Euler's method and the Runge-Kutta method. Eulerk method is simple in concept, but not of sufficient accuracy to be useful; it is included here because it illustrates the basic method of calculation and can be modified to yield methods of higher accuracy. The Runge-Kutta method, of which there are several variants, is the usual method of choice. A third method, the predictor-corrector method, will be described later in this chapter. Euler's Method Let us use in our first calculation an example of equation 10- 1 : the first-order kinetic process A + B with initial concentration CO = 0.2000 molL and rate constant k = 5 x s-'. We'll simulate the change in concentration of the species A vs. time over the interval from t = 0 to t = 600 seconds, in increments of 20 seconds.

218 EXCEL NUMERICAL METHODSdocview1.tlvnimg.com/tailieu/2011/20111104/banhbeo2/excel_for... · 218 EXCEL NUMERICAL METHODS ... 224 EXCEL NUMERICAL METHODS =2* ... The Runge-Kutta

  • Upload
    dodien

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 218 EXCEL NUMERICAL METHODSdocview1.tlvnimg.com/tailieu/2011/20111104/banhbeo2/excel_for... · 218 EXCEL NUMERICAL METHODS ... 224 EXCEL NUMERICAL METHODS =2* ... The Runge-Kutta

218 EXCEL NUMERICAL METHODS

and although writing the differential equation, such as the above, may be simple, solving the problem is not. By "solving," we mean that we want to be able to calculate the value of y for any value of x. Some differential equations, such as 10-1, are solvable by symbolic integration (the integrated equation is In y = -kt + const), but many others may not be amenable to solution by the "pencil-and- paper" approach. Numerical methods, however, can always be employed to find the value of the function at various values o f t . Although we haven't found an expression for the function F(x, y ) , but simply obtained a table of y values as a function of x, the process is often referred to as "integration."

You may remember from your freshman calculus class that when an expression is integrated, an arbitrary constant of integration is always part of the solution. For example, when equation 10- 1 is integrated, the result is In y = -kt + In yo, or yt = yoe-". A similar situation pertains when numerical methods are employed: to solve the problem, one or more values of the dependent variable and/or its derivative must be known at specific values of the independent variable. If these are given at the zero value of the independent variable, the problem is said to be an initial-value problem; if they are given at some other values of the independent variable, the problem is a boundary-value problem. This chapter deals with initial-value problems, while the following chapter deals with boundary-value problems.

Solving a Single First-Order Differential Equation

This section describes methods for solving first-order differential equations with initial conditions (the order of a differential equation is determined by the order of the highest derivative in the equation). Two methods will be described: Euler's method and the Runge-Kutta method. Eulerk method is simple in concept, but not of sufficient accuracy to be useful; it is included here because it illustrates the basic method of calculation and can be modified to yield methods of higher accuracy. The Runge-Kutta method, of which there are several variants, is the usual method of choice. A third method, the predictor-corrector method, will be described later in this chapter.

Euler's Method Let us use in our first calculation an example of equation 10- 1 : the first-order

kinetic process A + B with initial concentration CO = 0.2000 m o l L and rate constant k = 5 x s-'. We'll simulate the change in concentration of the species A vs. time over the interval from t = 0 to t = 600 seconds, in increments of 20 seconds.

Page 2: 218 EXCEL NUMERICAL METHODSdocview1.tlvnimg.com/tailieu/2011/20111104/banhbeo2/excel_for... · 218 EXCEL NUMERICAL METHODS ... 224 EXCEL NUMERICAL METHODS =2* ... The Runge-Kutta

CHAPTER 10 ORDINARY DIFFERENTIAL EOUATIONS. PART I 219

The differential equation for the change in concentration of the species A as a function of time is

d[ A] ldt = -k[ A] (1 0-4)

Expressing this in terms of finite differences, the change in concentration A[A] that occurs during the time interval from t = 0 to t = At is

A[A] = -k[A], At (1 0-5)

Thus, if the concentration of A at t = 0 is 0.2000 My then the concentration at t = (0 + At) is [A] = 0.2000 - (5 x lO")(O.2OOO)(2O) = 0.1800 M. The calculation, known as Euler's method, is illustrated in Figure 10-1. The formula in cell 87 is

=BG-k*BG*DX.

The concentrations at subsequent time intervals are calculated in the same way. In general, the formula is

Yfl + I = Yfl + hF(x,,, Yfl) ( 10-6)

where h = xfl - x,.

Figure 10-1. Simulation of first-order kinetics by Euler's method. (folder 'Chapter 10 Examples', workbook 'ODE Examples', worksheet 'Euler')

The advantage of Euler's method is that it can be easily expanded to handle systems of any complexity. It is not particularly useful, however, since the error introduced by the approximation d[A]ldt = A[A]/At is compounded with each additional calculation. Compare the Euler's method result in column B of Figure

Page 3: 218 EXCEL NUMERICAL METHODSdocview1.tlvnimg.com/tailieu/2011/20111104/banhbeo2/excel_for... · 218 EXCEL NUMERICAL METHODS ... 224 EXCEL NUMERICAL METHODS =2* ... The Runge-Kutta

220 EXCEL NUMERICAL METHODS

10-1 with the analytical expression for the concentration, [A], = in column C. At the end of approximately one half-life (seven cycles of calculation in this example), the error has already increased to 3.6%. Accuracy can be increased by decreasing the size of At, but only at the expense of increased computation. A much more efficient way of increasing the accuracy is by means of a series expansion. The Runge-Kutta methods, which are described next, comprise the most commonly used approach.

The Fourth-Order Runge-Kutta Method The Runge-Kutta methods for numerical solution of the differential equation

dyldx = F(x, y) involve, in effect, the evaluation of the differential function at intermediate points between x, and x,,+~. The value of ynCl is obtained by appropriate summation of the intermediate terms in a single equation. The most widely used Runge-Kutta formula involves terms evaluated at x,,, x,+~/x/~ and x,,+~. The fourth-order Runge-Kutta equations for dyldx = F(x, y) are

Ax Ti + 2Tz + 2T3 + T4

6 Yn+l =Yn + (1 0-7)

where

T3 = F(x,+ --,yn+ Ax -) T2 2 2

( 1 0-9)

(1 0-1 0)

T4 = F (xn + b, ~n + T3) (10-1 1)

If more than one variable appears in the expression, then each is corrected by using its own set of TI to T4 terms.

Fourth-Order Runge-Kutta Method Implemented on a Worksheet

The spreadsheet in Figure 10-2 illustrates the use of the RK method to simulate the first-order kinetic process A + By again using initial concentration [Ale = 0.2000 and rate constant k = 5 x The differential equation is, again, equation 10-4. This equation is of the simple form dyldx = F(y), and thus only they, terms of TI to T4 need to be evaluated. The F K terms (note that TI is the Euler method term) are shown in equations 10-12 through 10-15.

Page 4: 218 EXCEL NUMERICAL METHODSdocview1.tlvnimg.com/tailieu/2011/20111104/banhbeo2/excel_for... · 218 EXCEL NUMERICAL METHODS ... 224 EXCEL NUMERICAL METHODS =2* ... The Runge-Kutta

CHAPTER 10 ORDINARY DIFFERENTIAL EOUATIONS. PART I 22 1

( 10- 12)

(10-13)

(10-14)

(1 0- 15)

Figure 10-2. Simulation of first-order kinetics by the Runge-Kutta method. (folder 'Chapter 10 Examples', workbook 'ODE Examples', worksheet 'MI')

The RK equations in cells 87, C7, D7, E7 and F7, respectively, are (only part of the spreadsheet is shown; the formulas extend down to row 74):

=-k*FG*DX

=-k*( FG+TAl /2)*DX

=- k*( F6+TA2/2)*DX

=-k*( F6+TA3)*DX

=FG+(TAI +2*TA2+2*TA3+TA4)/6.

If you use the names TA1, . . ., TA4 you can use AutoFill to generate the column labels TA1, . . ., TA4. These names are accepted by Excel, whereas T1 is not a valid name. As well, the nomenclature is expandable to systems requiring more than one set of Runge-Kutta terms (e.g., TB1, . . ., TB4, etc.).

Compare the RK result in column F of Figure 10-2 with the analytical expression for the concentration, [A]t = in column G. After one half-life (row 13) the RK calculation differs from the analytical expression by only

Page 5: 218 EXCEL NUMERICAL METHODSdocview1.tlvnimg.com/tailieu/2011/20111104/banhbeo2/excel_for... · 218 EXCEL NUMERICAL METHODS ... 224 EXCEL NUMERICAL METHODS =2* ... The Runge-Kutta

222 EXCEL NUMERICAL METHODS

0.00006%. (Compare this with the 3.6% error in the Euler method calculation at the same point.) Even after 10 half-lives (not shown), the RK error is only 0.0006%.

In essence, the fourth-order Runge-Kutta method performs four calculation steps for every time interval. The percent error after one half-life ( t = 140) is only 6 x In contrast, in the solution by Euler's method, decreasing the time increment to 5 seconds to perform four times as many calculation steps still only reduces the error to 0.9% after 1 half-life.

If the spreadsheet is constructed as shown in Figure 10-2, you can't use a formula in which a name is assigned to the values of the calculated concentration in column F (the range $F$7:$F$74). This is because the formula in 87, for example, will use the concentration in F7; this is called an implicit intersection. An alternative arrangement that permits using a name for the concentration [A], is shown in Figure 10-3. Each row contains the concentration at the beginning and at the end of the time interval. The name C-t can now be assigned to the array of values in column B; the former formulas (now in cells $C$7:$G$74) contain C-t in place of F6 and cell 87 contains the formula =G6.

Figure 10-3. Alternative spreadsheet layout for the Runge-Kutta method. (folder 'Chapter 10 Examples', workbook 'ODE Examples', worksheet 'RK2')

The RK equations in cells C6, D6, E6, F6 and G6, respectively, are

=-k*C-t*DX

=-k*(C_t+TAl/2)*DX

=-k*( CWt+TA2/2)*DX

Page 6: 218 EXCEL NUMERICAL METHODSdocview1.tlvnimg.com/tailieu/2011/20111104/banhbeo2/excel_for... · 218 EXCEL NUMERICAL METHODS ... 224 EXCEL NUMERICAL METHODS =2* ... The Runge-Kutta

CHAPTER 10 ORDINARY DIFFERENTIAL EQUATIONS. PART I 223

=-k*( C_t+TA3)*DX

= C-t+ (TA 1 +2 *TA2 +2*TA3 +TA4)/6

and cell 87 contains the formula =G6.

Fourth-Order Runge-Kutta Method Applied to a Differential Equation Involving Both x and y

In the preceding examples, the differential equation involved only the dependent variable y. In the general case, the differential equation can be a function of both x and y. The following example illustrates the use of the Runge- Kutta method for dyldx = F ( x , y).

A function is described by the differential equation

dyldx = 2x2 + 2y (1 0-1 6)

and the function has the value y = 0.5 at x = 0. We want to find the value of the function over the range x = 0 to x = 1. Figure 10-4 illustrates the use of the RK method to model the function. The formulas for the TI-T~ terms, in cells B11 to E l 1 are, respectively,

=2*A10A2+2*F10

=2*(A1 O+deltax/2)"2+2*(FI O+BI 1 *deltax/2)

=2*(A1 O+delta~/2)~2+2*( F1 O+C11 *deltax/2)

Figure 10-4. The fourth-order Runge-Kutta method applied toy' = 2x2+2y. (folder 'Chapter 10 Examples', workbook 'ODE Examples', worksheet 'Both x and y (Formulas)')

Page 7: 218 EXCEL NUMERICAL METHODSdocview1.tlvnimg.com/tailieu/2011/20111104/banhbeo2/excel_for... · 218 EXCEL NUMERICAL METHODS ... 224 EXCEL NUMERICAL METHODS =2* ... The Runge-Kutta

224 EXCEL NUMERICAL METHODS

=2*(A1 O+delta~)~2+2*(FI O+DI l*deltax)

and the formula for yn+1, in cell F11, is

=F10+(B11+2*C11+2*DIl+El l)*deltax/G

Figure 10-4 shows the agreement between the RK values and the exact values (the unknown function is y = eb - x2 - x - 0.5). The errors are small and increase only slowly with increasing x.

Fourth-Order Runge-Kutta Custom Function for a Single Differential Equation with the Derivative Expression Coded in the Procedure

The Runge-Kutta formulas can be implemented in the form of a VBA custom function. The VBA code is shown in Figure 10-5.

This first version can handle a single first-order ordinary differential equation; the expression for the derivative must be "hard-wired" in the VBA code. The syntax of the function is Runge(x-variable, y-variable, interval). The function returns the value of y (the dependent variable) at x + Ax, based on the values of x (the independent variable), y and a differential equation. The arguments x-variable and y-variable are references to cells containing the values of x and y in the derivative expression coded in the subroutine. The argument interval is a value or cell reference or formula that specifies the interval of x over which the Runge-Kutta integration is to be calculated.

Option Explicit Function Runge(x-variable, y-variable, interval) 'Runge-Kutta method to solve a single first-order ODE. 'Expression for derivative must be coded in subroutine. Dim T I As Double, T2 As Double, T3 As Double, T4 As Double ' Calculate the RK terms T I = interval * deriv(x-variable, y-variable) T2 = interval * deriv(x-variable + interval / 2, y-variable + T I /2) T3 = interval deriv(x-variable + interval /2, y-variable + T2 / 2) T4 = interval deriv(x-variable + interval, y-variable + T3) Runge = y-variable + (TI + 2 * T2 + 2 * T3 + T4) / 6 End Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Function deriv(X, Y) 'Code the derivative here. deriv = 2 * X A 2 + 2 * Y End Function

Figure 10-5. Simple custom function for Runge-Kutta calculation. (folder 'Chapter 10 Examples', workbook 'ODE Examples', module 'SimpleRungeKutta')

Page 8: 218 EXCEL NUMERICAL METHODSdocview1.tlvnimg.com/tailieu/2011/20111104/banhbeo2/excel_for... · 218 EXCEL NUMERICAL METHODS ... 224 EXCEL NUMERICAL METHODS =2* ... The Runge-Kutta

CHAPTER 10 ORDINARY DIFFERENTIAL EQUATIONS. PART I 225

Figure 10-6 illustrates the use of the custom function. The formula in cell C9

=Runge(A8,C8,A9-A8)

is

Figure 10-6. The fourth-order Runge-Kutta method applied toy' = 2r2+2y by using a user-defined function.

(folder 'Chapter 10 Examples', workbook 'ODE Examples', worksheet 'Both x and y (Simple RK function)')

In following sections, procedures will be provided to handle systems of simultaneous differential equations. In addition, the VBA code will be modified so that the expression for the derivative is passed to the function as an argument.

Fourth-Order Runge-Kutta Custom Function for a Single Differential Equation with the Derivative Expression Passed as an Argument

The custom function Runge described in the preceding section simplifies the solution of an ordinary differential equation, but the VBA code must be modified for each case. The custom function to be described next permits the user to enter the expression for the derivative as an Excel formula in a worksheet cell and pass the expression to the custom function as an argument. This custom function uses the method employed in previous chapters: the Formula property is used to obtain the formula of (in this case) the derivative, the SUBSTITUTE function to replace a cell reference in the formula with a value, and the Evaluate method to calculate the value of the function. The VBA code is shown in Figure 10-7. The syntax of the function is Rungel (x-variable, y-variable, deriv-formula, interval). The arguments x-variable (the independent variable), y-variable (the dependent variable) and interval are as described in the previous section; the

Page 9: 218 EXCEL NUMERICAL METHODSdocview1.tlvnimg.com/tailieu/2011/20111104/banhbeo2/excel_for... · 218 EXCEL NUMERICAL METHODS ... 224 EXCEL NUMERICAL METHODS =2* ... The Runge-Kutta

226 EXCEL NUMERICAL METHODS

argument deriv-formula is a reference to a cell containing the derivative in the form of worksheet formula.

A more advanced version that handles multiple differential equations will be presented later.

Option Explicit Function Rungel (x-variable, y-variable, deriv-formula, interval) 'Runge-Kutta method to solve ordinary differential equations. 'Solves problems involving a single first-order differential equation. 'Derivative expression passed as an argument.

Dim FormulaText As String Dim XAddress As String, YAddress As String Dim X As Double, Y As Double Dim H As Double, result As Double

'GET THE FORMULA AND REFERENCE ARGUMENTS FormulaText = deriv-formula.Formula 'Make all references absolute FormulaText = Application.ConvertFormula(FormulaText, xlAl , xlAl , - xl Absolute) XAddress = x-variable.Address 'absolute is default X = x-variable.Value YAddress = y-variable.Address 'absolute is default Y = y-variable.Value Rungel = RKI (XAddress, YAddress, X, Y, interval, FormulaText) End Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Private Function RKI (XAddress, YAddress, X, Y, H, FormulaText) ' Calculate the RK terms Dim T I As Double, T2 As Double, T3 As Double, T4 As Double Dim result As Double

Call eval(XAddress, YAddress, X, Y, FormulaText, result) T I = result H Call eval(XAddress, YAddress, X + H I 2, Y + T I / 2, FormulaText, result) T2 = result * H Call eval(XAddress, YAddress, X + H 12, Y + T2 12, FormulaText, result) T3 = result * H Call eval(XAddress, YAddress, X + H, Y + T3, FormulaText, result) T4 = result * H RKI = Y + (TI + 2 *T2 + 2 * T3 + T4) 16 End Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Sub eval(XRef, YRef, XValue, Walue, ForrnulaText, result) 'Evaluates the derivative formula. Replaces each instance of, e.g., $A$2 in formula with number value, e.g., 0.20, then evaluates. 'Must do this replacement from end of formula to beginning. 'Modified 03/08/06 to handle possible un-intended replacement of e.g., $A$2 in $A$22. 'Method: replace $A$2 with value & " " 'so that $A$22 becomes "0.20 2" and this formula evaluates to an error.

Page 10: 218 EXCEL NUMERICAL METHODSdocview1.tlvnimg.com/tailieu/2011/20111104/banhbeo2/excel_for... · 218 EXCEL NUMERICAL METHODS ... 224 EXCEL NUMERICAL METHODS =2* ... The Runge-Kutta

CHAPTER 10 ORDINARY DIFFERENTIAL EQUATIONS. PART I 227

I

Dim T As String, temp As String Dim NRepl As Integer, J As Integer Dim dummy As Double

T = FormulaText 'First, do substitution of all instances of x address with value NRepl = (Len(T) - Len(Application.Substitute(T, XRef, I"'))) I Len(XRef) For J = NRepl To 1 Step -1

temp = Application.Substitute(T, XRef, XValue & " ", J) On Error GoTo ErrorHandlerl dummy = Evaluate(temp) T = temp

ptl: Next J 'Then do substitution of all instances of y address with value NRepl = (Len(T) - Len(Application.Substitute(T, YRef, ""))) I Len(YRef) For J = NRepl To 1 Step -1

temp = Application.Substitute(T, YRef, YValue 81 " ", J) On Error GoTo ErrorHandlerZ dummy = Evaluate(temp) T = temp

pt2: Next J result = Evaluate(T) Exit Sub

'ERROR HANDLER ROUTINES. ErrorHandlerl : 'Trappable error number 13 (Type mismatch) is expected. If Err.Number = 13 Then

On Error GoTo 0 Resume ptl 'and continue execution.

Else End

End If ErrorHandlerZ: If Err.Num ber = 13 Then

'Disable the error handler.

'Some other error, so quit completely

On Error GoTo 0 Resume pt2

Else End

End If End Sub

Figure 10-7. Custom function for Runge-Kutta calculation. (folder 'Chapter 10 Examples', workbook 'ODE Examples', module 'RungeKuttal')

In Figure 10-8, the custom function is applied to the same first-order reaction kinetics problem that was calculated on a worksheet in the preceding sections. The formulas in cells C6 and D7 are, respectively,

=-k*D6

and = R u nge 1 (A6, D6, C6, A7-A6)