Page 247 - Excel for Scientists and Engineers: Numerical Methods
P. 247
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 TI As Double, T2 As Double, T3 As Double, T4 As Double
' Calculate the RK terms
TI = interval * deriv(x-variable, y-variable)
T2 = interval * deriv(x-variable + interval / 2, y-variable + TI /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')