Foundations of Excel VBA Programming and Numerical Methods PDF
Foundations of Excel VBA Programming and Numerical Methods PDF
Garber
ISBN 978-5-91146-894-1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Chapter 1. Programming in Visual Basic . . . . . . . . . . . . . . . . . . . 12
1.1. Elements of Visual Basic Environment. . . . . . . . . . . . . . . . 13
1.2. Main commands of the program debugger. . . . . . . . . . . . . . 19
1.3. Variables. Data types . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.4. Two main functions for conversion of data types . . . . . . . . . . 27
1.5. Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.6. Obtaining information . . . . . . . . . . . . . . . . . . . . . . . . 32
1.7. Assignment operator . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.8. Arithmetic expression. . . . . . . . . . . . . . . . . . . . . . . . . 38
1.9. Mathematical functions. Functions of date and time . . . . . . . . . 45
1.10. Logical expression . . . . . . . . . . . . . . . . . . . . . . . . . . 48
1.11. GoTo operator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
1.12. Decision-making constructs. . . . . . . . . . . . . . . . . . . . . . 53
1.13. Cycles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
1.14. Manifestation of the error of real numbers’ computer representation 65
1.15. Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
1.16. User-defined procedures . . . . . . . . . . . . . . . . . . . . . . . 77
1.17. Built-in procedures. Usage of standard windows. . . . . . . . . . . 85
1.18. Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
1.19. Work with strings. . . . . . . . . . . . . . . . . . . . . . . . . . . 94
1.20. Work with text files. . . . . . . . . . . . . . . . . . . . . . . . . . 101
1.21. Matrix terminology. Formulation of demonstration tasks . . . . . . 109
1.22. Program for transposing a matrix relative to its auxiliary diagonal . 111
1.23. User-defined forms . . . . . . . . . . . . . . . . . . . . . . . . . . 116
1.24. Digression. Developing programs with the form in Microsoft
Visual Studio. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Chapter 2. Programming in VBA . . . . . . . . . . . . . . . . . . . . . . . 133
2.1. Loading the form from the Excel window. Running the program
executable file. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
4
Contents
5
Contents
6
Contents
7
Introduction
8
Introduction
In the third chapter, we consider the finite difference method for solving the
second-order linear differential equation with two kinds of conditions on the
solution, namely, the boundary and periodicity conditions. This is followed by
a review of two versions of the decomposition method for solving systems of
linear algebraic equations of special form called finite difference schemes. The
simplest scheme is also solved by the Gaussian elimination method. The ques-
tion of stability of the decomposition and Gaussian methods is investigated in
respect of not increasing the computing error during solving the scheme. Using
the Shockley-Poisson equation as an example, we consider the quasilinearization
method for solving the nonlinear differential equation with boundary conditions.
To demonstrate the possibilities of the finite difference method, we develop sub-
routines and programs for solving mathematical and applied problems. We use
the Excel scatter diagrams for visualization of calculation results.
Chapter 4 is devoted to the use of the third-degree (cubic) spline:
for interpolation, differentiation and integration of tabular (grid) func-
tions;
for solving the nonlinear algebraic and linear differential equations.
Besides, we consider:
two classical methods for solving the nonlinear algebraic equations,
namely, the bisection and secant methods;
the locally one-dimensional scheme for solving the heat equation with
two spatial coordinates.
We solve a series of applied problems to demonstrate the possibilities of the
cubic spline construction. In addition to the macros and user-defined procedures
(subroutines and function) realizing the numerical methods, a subroutine for
automatic creation of graphs is developed.
In Chapter 5, we review the use of the second-degree (quadratic) spline for
solving the initial value problem (of Cauchy) for the system of differential equa-
tions. The first-degree (linear) spline is used in the least-squares method intended
for determining parameters of a function. Besides, we review the following
methods:
the Newton method for solving the system of nonlinear algebraic equa-
tions;
the tangent, secant and Steffensen methods (called Newton-like methods)
for solving a single nonlinear algebraic equation;
methods for the forward and backward discrete Fourier transforms of
a periodic function.
Based on this theoretical material, we develop procedures and programs for
solving applied problems.
Chapter 6 is mainly devoted to nonlinear programming, more precisely, to
the question of finding the minimum of a nonlinear function of one or several
9
Introduction
10
Introduction
11
Chapter 1.
Programming in Visual Basic
12
1.1. Elements of Visual Basic Environment
For writing and debugging programs, we will use Visual Basic Environment,
which is a part of Microsoft Office.
Program debugging involves detection and correction of errors that, as a rule,
are present in a program text just written.
To go to Visual Basic Environment, we must fulfill the following two opera-
tions:
1) in the Excel window (with the active workbook by name Book1), activate
the Developer tab by clicking on it;
2) click on the Visual Basic button in area Code.
As a result, the Visual Basic Environment window is displayed (Fig. 1.1).
In this window, we can perform various actions: entering and editing the pro-
gram text, as well as debugging and executing the program. Further, we will use
a shorter name for this window and call it “the VB window”.
The program is also called an application or project. It will be in the Excel
workbook (by name Book1).
Let us consider the elements of the VB window.
1. Menu bar. There are standard menus, like in many windows of the
operating system: File, Edit, View, Tools and Help. The Insert menu is used
for organizing a place for program storage (in the workbook). Menus Debug
and Run are respectively used for debugging and running the program.
2. Context menu. It serves for convenience of work in the area (of the VB
window), in which the mouse pointer is located.
For using the context menu:
1) place the mouse pointer in the necessary area of the screen and make the
right click;
2) click (by the left mouse button) on the required command of the displayed
menu.
3. Toolbars: Standard, Edit, Debug and others. Only the standard toolbar is
displayed by default. To add or remove any toolbar, we have to fulfill View >
Toolbars and to click on the required command of the displayed menu. The
check (tick) mark against the command testifies to the presence of the corre-
sponding toolbar on the display screen.
13
Chapter 1. Programming in Visual Basic
Fig. 1.1. The Visual Basic Environment window including the standard
toolbar, the project explorer window and the properties window
14
1.1. Elements of Visual Basic Environment
15
Chapter 1. Programming in Visual Basic
For opening the code window corresponding to the module inserted earlier,
we have to click twice on the name of this module in the project explorer
window.
To delete a module:
1) make the right click on the module name (for example Module1) in the
project explorer window;
2) in the context menu opened, click on the Remove command;
3) click on the No button in the open window with a question about export-
ing the module before removing it.
Before the computer will execute a program, we (as the program developer)
must form its text in the code window. The first and last lines (operators) of the
program are standard:
Sub name()
End Sub
On p. 79, we will consider the origin of word Sub. Word name means the
program name appointed by us.
The name must satisfy the following conditions:
the first character should be a letter;
the name must include only letters, figures and the underscore character;
the name must include less than 256 characters.
As we see, the name cannot include the space character. To use name
consisting of several words, we have:
to begin each word with a capital (uppercase) letter;
to use the underscore character instead of the space character.
Examples of the program name follow:
MyProgram13
my_program
MyProgram_13
Between the first and last lines of the program, we have to place other lines
(operators) of this program. For that, it is possible to use Windows Clipboard and
habitual commands of editing (as in Notepad). After typing a new line, we have
to press the Enter key on the keyboard.
Let us start with a simple program based on the Pythagoras theorem,
c a 2 b2 , (1.1)
for calculating length c of the hypotenuse of a right-angled triangle with legs
a = 3 and b = 4.
16
1.1. Elements of Visual Basic Environment
In the code window, we type the following program text (Fig. 1.3):
Sub Pythagoras()
a = 3
b = 4
c = Sqr(a ^ 2 + b ^ 2)
End Sub
In this text, Pythagoras is the program name, a, b and c are names of varia-
bles, Sub is a keyword, End Sub is a keyword combination. The program and
variable names are appointed by us.
Fig. 1.3. The VB window with the Pythagoras program in the code window
17
Chapter 1. Programming in Visual Basic
Sub Pythagoras()
a = 3: b = 4
c = _
Sqr(a ^ 2 + b ^ 2) 'according to Pythagoras
End Sub
Sub Pythagoras()
a = 3: b = 4
c = Sqr(a ^ 2 + b ^ 2) 'according to Pythagoras:
'pythagorean pants are
'equal in all directions
End Sub
18
1.2. Main commands of the program debugger
After typing the program text, the detection and correction of errors in the
program follows. At this stage, we can use the debugger.
Let us consider the main commands of the debugger; we can see them in the
Debug menu of the VB window.
1. Step Into — the execution of one program operator or its part. The click
on Step Into is equivalent to pressing the F8 key on the keyboard. This command
is used for the step-by-step program execution.
2. Run To Cursor — the execution of the program up to the blinking cursor.
The click on Run To Cursor is equivalent to pressing Ctrl + F8.
For setting the blinking cursor in the proper place of the program, we have to
click on this place.
If we speak about key presses, the plus sign means the synchronism of these
presses, i.e., “pressing Ctrl + F8” means “simultaneous pressing the Ctrl and F8
keys”.
3. Toggle Breakpoint — the installation or liquidation of the breakpoint at
the place, where the blinking cursor is located. The breakpoint marks the pro-
gram line, where the program execution stops. This command can also be per-
formed by pressing the F9 key.
For the installation or liquidation of the breakpoint, we can click on the left
border of the code window against the proper line.
4. Clear All Breakpoints — the liquidation of all breakpoints. This com-
mand can also be performed by pressing Ctrl + Shift + F9.
5. Add Watch — the current visualization of the value of a variable. We will
review the command usage in Section 1.15.
In addition to commands Step Into and Run To Cursor, two more commands
for the program execution, Step Over and Step Out, are in the Debug menu. We
will review them in Section 1.16.
Let us consider commands Run and Reset located in the Run menu of the VB
window.
1. Run — the start of the program execution (or shorter, of the program) and
transition from one breakpoint to another. If the breakpoints are absent, the pro-
gram is executed completely. This command is represented by arrow ► on the
toolbars of the VB window, in particular, on the standard toolbar.
19
Chapter 1. Programming in Visual Basic
The program can be started from the Excel window; we will consider this
possibility later (p. 113).
2. Reset — the discontinuation of the program execution. This command is
represented by square ■ on the toolbars.
During the program execution stops (in particular, at the breakpoints), yellow
color highlights the operator, which is not executed yet. If we place the mouse
pointer on a variable, its value is displayed.
For obtaining the hypotenuse length by means of the Pythagoras program
from the previous section, we fulfill the following:
1) click on the left border of the code window against the last line of the
program for marking this line by the breakpoint (Fig. 1.4a);
2) click on arrow ► for executing the Pythagoras program up to the
breakpoint;
3) if window Macros appears, successively click on the Pythagoras line and
the Run button in this window;
4) in the code window, whose state is depicted in Fig. 1.4b, place the mouse
pointer on the c variable in the program text; c = 5 appears (Fig. 1.5);
5) click on arrow ► for terminating the program execution.
After starting the program execution, a window containing message Can’t
execute code in break mode may appear, indicating that we forgot to terminate
(or to discontinue) the previous program execution. For correcting this error, we
fulfill the following:
1) click on the OK button in the message window;
2) click on arrow ► (or on square ■) for termination (or discontinuation) of
the program execution;
3) restart the program.
The program execution means consecutive execution of its operators: at first,
the computer sets the values of variables a and b, and then calculates the value
of c. To be convinced, we have to liquidate the breakpoint (by clicking on it) and
to execute the Pythagoras program step-by-step by the F8 key, watching the
change in variables a, b and c.
Let us assume that an error was committed: when typing operator
c = Sqr(a ^ 2 + b ^ 2)
we pressed the minus key on the keyboard instead of the plus key. In this case,
the program execution stops, and a window appears with the following message:
Run-time error ‘5’: Invalid procedure call or argument.
To understand our error, we click on button Debug in the message window.
As a result, the place, where the stop occurred, is highlighted in yellow color.
Looking at the values of a and b, we can understand the reason of the stop — the
negative value of the argument of the square root function.
20
1.2. Main commands of the program debugger
Fig. 1.5. The visualization of the value of c during the execution stop
21
Chapter 1. Programming in Visual Basic
For fuller information on the possible reasons of the stop, we fulfill the fol-
lowing:
1) remaining in Visual Basic Environment, start the Excel help system by
pressing the F1 key;
2) type Error 5 in the text box of the Excel Help window;
3) click on the Search button;
4) click on the following line of the open list: Invalid procedure call or
argument (Error 5).
After correcting our error (that is, after changing minus to plus), we have to
restart the program.
During the execution, our program (as a set of zeros and units) is located in
the main memory of the computer. This program is being executed by the pro-
cessor that performs different operations including, among others, arithmetic
operations.
Now we will pass to the Visual Basic programming language.
22
1.3. Variables. Data types
23
Chapter 1. Programming in Visual Basic
Option Explicit
We can also put this line into the code window (or remove it) manually, as
a usual program line.
In the presence of line Option Explicit, the computer diagnoses the use
of an undeclared variable in the program text: during the program execution, the
computer displays message Variable not defined.
Data types Byte, Integer, Long, Currency, Single and Double
(Appendix 1) are called numerical data types.
According to the third column of the table in Appendix 1:
in a memory cell, corresponding to a variable of the Byte data type, non-
negative integers (up to 255) can only be stored;
in a cell, corresponding to a variable of the Integer or Long data type,
integers can be stored;
in a cell, corresponding to a variable of the Currency, Single or
Double data type, decimal numbers can be stored.
Let us pass to the second version of the Dim operator (p. 23).
If we do not specify the data type when declaring a variable (for example, by
operator Dim W), the variable (by name W) automatically receives the Variant
data type. It means that any information can be stored in a memory cell, corre-
24
1.3. Variables. Data types
sponding to this variable; i.e., the Variant data type is similar to the general
format of Excel.
Let us consider operator
Dim i, j As Integer
If we need the Integer data type for both variables, i and j, we should
declare them as follows:
or
Dim i As Integer
Dim j As Integer
Later we will consider ways of declaring variables without the use of the Dim
keyword (p. 81).
As an example of using the declaration operator, let us consider the following
program for calculating the number of days in the 20th century and defining the
current date and time:
Listing 1.1
Sub Century_20()
Dim D1 As Date, D2 As Date, D3 As Date
Dim N As Long
D1 = #1 Jan 1900# 'beginning date of century
D2 = #31 Dec 1999# 'ending date of century
N = D2 - D1 + 1 'number of days in century
D1 = Time 'current time
D2 = Date 'current date
D3 = Now 'date and time
End Sub
In the second and third lines of this program, Date and Long are the data
types (Appendix 1); #1 Jan 1900# and #31 Dec 1999# mean dates on Janu-
ary 1, 1900 and December 31, 1999. The subtraction of the first date from the
second date determines the number of days between these dates.
25
Chapter 1. Programming in Visual Basic
D2 = Date
word Date means the call of the Date function returning the current date into
the program.
We see that Date is a name of the VB function and a name of the data type.
Thanks to various contexts, it does not lead to confusion.
Word Now means the call of the Now function returning the current date and
time together.
Regarding the VB functions, we will talk in more details later, in particular,
in Sections 1.4 and 1.9.
To be convinced of the operational capability of the Century_20 program,
we fulfill the following operations:
1) insert a module into the active Excel workbook (p. 15);
2) enter the Century_20 program text into the code window of the new
module;
3) make the step-by-step execution of this program by means of the F8 key,
watching the values of variables D1, D2, D3 and N.
It should be emphasized that, before the first press of key F8, we must place
the blinking cursor inside the program text, not in line Option Explicit.
Text Listing 1.1 of the Century_20 program can be entered into the code
window by means of the keyboard. We can also copy it from the enclosed CD.
For copying:
1) open file Listing_1_01.txt with the Notepad editor, for example, by dou-
ble click on the pictogram of this file in Windows Explorer;
2) in the Notepad window opened, highlight the program text and copy it
into Windows Clipboard, for example, by pressing Ctrl + C;
3) by the click, locate the blinking cursor in the code window of Visual
Basic Environment;
4) paste the program text from Windows Clipboard into the code window,
for example, by pressing Ctrl + V;
5) close the Notepad window with file Listing_1_01.txt.
26
1.4. Two main functions for conversion of data types
27
Chapter 1. Programming in Visual Basic
strA = Str(curB)
curB = Val(strA)
28
1.5. Constants
1.5. Constants
In this operator:
Const is the keyword testifying the appearance of a new constant;
invariable is the constant name;
As is the keyword, as in the Dim operator (p. 23);
type is the data type (Appendix 1) of the declared constant;
value is a value of the declared constant.
The restrictions on names of constants are the same as on names of variables
and programs (p. 16).
Examples of the constant declaration follow:
In the fourth example operator, Boolean is the so-called logical data type
(Appendix 1).
When executing the last operator, the rounded square root of 2 (that is,
1.4142) is assigned to constant beta. This example shows that value in the
Const operator can be an elementary arithmetic or logical expression (Sec-
29
Chapter 1. Programming in Visual Basic
tions 1.8 and 1.10). In this case, the content of the memory cell, corresponding to
the constant, is determined by the expression value rounded according to the
type data type.
One Const operator allows declaring several constants if we list them
through a comma. The example operator follows:
Sub deg2rad()
Dim angleD As Double
Dim angleR As Double
Const pi As Double = 3.141592654 'pi = tau / 2
angleD = 270 'angle equals 270 degrees
angleR = angleD * pi / 180
'result: angle in radians
End Sub
As we see, operator
Sub rad2deg()
Dim angleD As Double
Dim angleR As Double
Const pi180 As Double = 3.141592654 / 180
angleR = 4.5 'angle equals 4.5 radians
angleD = angleR / pi180
'result: angle in degrees
End Sub
30
1.5. Constants
The built-in constant does not need any declaration. Names of the built-in
constants of Visual Basic begin with prefix vb, for example, vbFriday (this con-
stant equals 6).
For names (in particular, names of constants), the developers of Windows
accepted the following agreement: names of similar data begin with the same
short prefix. In particular, the built-in constants of Visual Basic have prefix vb,
the built-in constants of Excel have prefix xl.
In addition to vbFriday, we will come across the following built-in constants:
vbYesNo, vbYes, vbTab, vbCrLf, vbCr, vbLf, xlR1C1, xlCalculationAutomatic,
xlCalculationManual, xlDialogOpen, xlDialogSaveAs, xlCenter, etc.
31
Chapter 1. Programming in Visual Basic
32
1.6. Obtaining information
The Excel help system, started by pressing the F1 key, is useful too (p. 22).
For accelerating the process of finding the necessary information, the blinking
cursor must be preliminarily located on the word of interest.
By means of the Excel help system, we will study the Val function. For this
purpose, let us fulfill the following.
1. Enter the StrVal program (p. 27) into the code window.
2. Locate the blinking cursor on the Val word by clicking on it.
3. Press the F1 key. As a result, the Excel Help window, containing the full
information on the Val function, is displayed (Fig. 1.8).
4. After studying the last information, copy fragment
Dim MyValue
MyValue = Val("2457") ' Returns 2457.
MyValue = Val(" 2 45 7") ' Returns 2457.
MyValue = Val("24 and 57") ' Returns 24.
from the bottom part of the Excel Help window into the StrVal program as
follows:
33
Chapter 1. Programming in Visual Basic
Fig. 1.8. The Excel Help window with information on the Val function
34
1.6. Obtaining information
Sub StrVal()
Dim strA As String
Dim curB As Currency
strA = "45.77"
curB = Val(strA) 'result: curB = 45.77
strA = Str(curB) 'result: strA = " 45.77"
curB = Val("4.7 = X") 'result: curB = 4.7
curB = Val("4,7 = X") 'result: curB = 4
curB = Val("X = 4.7") 'result: curB = 0
curB = Val("") 'result: curB = 0
Dim MyValue
MyValue = Val("2457") ' Returns 2457.
MyValue = Val(" 2 45 7") ' Returns 2457.
MyValue = Val("24 and 57") ' Returns 24.
End Sub
We advise the reader to execute this program step-by-step (by means of the
F8 key), watching the value of the MyValue variable.
35
Chapter 1. Programming in Visual Basic
variable = expression
Sub Conversion()
Dim curA As Currency
Dim curB As Currency
Dim curC As Currency
curA = "78.8" 'result: curA = 78.8
curB = "78,8" 'result: curB = 78.8
curC = "78;8" 'result is absent
End Sub
36
1.7. Assignment operator
curC = "78;8"
the stop occurs with the following information: Run-time error ‘13’: Type mis-
match. It speaks about the following:
the types of variable on the left and of value on the right of the assign-
ment sign (=) are different;
the computer cannot convert string "78;8" to a number.
We will continue considering the data type conversion in the next section of
the book.
Unlike other programming languages, for example C++, multiple assign-
ments, for example x = y = z = 1.3, are inadmissible in VB. We have to use
several assignment operators with the same right-hand side, i.e., language con-
struct
x = 1.3
y = 1.3
z = 1.3
or
is correct.
37
Chapter 1. Programming in Visual Basic
–18 32 0
If a number has the fractional part, it separates from the integral part by
a point. In this case, we may omit the integral part if it equals zero. Examples
of decimal numbers follow:
In the last example, 3 with a point means a number with zero fractional part, i.e.,
an integer, in fact.
We reviewed the main form of decimal numbers.
Decimal numbers may also be represented in exponential form. For example,
-1.6E-19 is the electron charge, -1.6·10-19 C (its absolute value is figured in
Section 3.13). Instead of E, letter D may be used in the exponential representa-
tion, i.e., the electron charge, -1.6·10-19 C, may be written as -1.6D-19
One of the main constructs of any programming language is an arithmetic
expression similar to the algebraic expression in mathematics. However, we can-
not omit the multiplication sign in the arithmetic expression. Table 1 below con-
tains equivalent algebraic and arithmetic expressions.
38
1.8. Arithmetic expression
z = 5 * x + 12 * y
5 * x + 12 * y
Sub Arithmetic1()
Dim m As Integer
Dim n As Integer
Dim x As Double
m = 5
n = 2
x = m / n 'result: x = 2.5
x = m \ n 'result: x = 2
x = m Mod n 'result: x = 1
End Sub
To verify the correctness of this program, we advise the reader to make the
step-by-step execution (by means of the F8 key), watching the change in the
value of x.
If the arithmetic expression contains several operations, the order of their per-
formance is defined by the following rules of priorities of arithmetic operations:
1) first of all, the power operation (^) is performed;
2) next, the multiplication and division (*, /) are performed in that sequence
as they are in the expression;
39
Chapter 1. Programming in Visual Basic
=-1^2
into the Excel formula box and click on the tick button of the Excel formula bar
(or press the Enter key). As a result, value 1 appears in the active cell on the
worksheet. After the execution of VB operators
Dim i As Integer
i = -1 ^ 2
z = 5 * x + 12 * y
40
1.8. Arithmetic expression
Algebraic
Arithmetic expression of VB
expression
7{3[a+b(c+d)]+8}+2 7 * (3 * (a + b * (c + d)) + 8) + 2
-a ^ b
-ab or
–(a ^ b)
a-b a ^ (-b)
ab-c a ^ (b - c)
10-4.7 10 ^ (-4.7)
104.7 10 ^ 4.7
A·B A * B
A * (-B)
-A * B
A(-B)
or
-(A * B)
c
ab a ^ (b ^ c)
a ^ b ^ c
(ab )c or
(a ^ b) ^ c
a b (a * b) / (c * d)
or
c d a * b / (c * d)
a * 1E4
a * 10E3
a ·104
or
a * 10000
41
Chapter 1. Programming in Visual Basic
Sub Arithmetic2()
Dim m As Integer
Dim n As Integer
Dim x As Single
Dim y As Single
x = 3
m = 2
n = -1
y = (-3) ^ m 'result: y = 9
y = -(3 ^ m) 'result: y = -9
y = -3 ^ m 'result: y = -9
y = 10 + (x + 7) ^ (m + n) 'result: y = 20
y = 10 + x + 7 ^ m + n 'result: y = 61
End Sub
(m \ n) * n + m Mod n
equals m for arbitrary integers m and n (naturally, n ≠ 0). For that, the reader has
to write a program, which is similar to Arithmetic1, and to execute the new
program step-by-step.
Arithmetic expressions may contain variables and invariables of different
types. If the type of the value of arithmetic expression in the right-hand side of
the assignment operator (on the right of sign =) does not coincide with the data
type of the variable in the left-hand side of the assignment operator (on the left of
sign =), the type of the value is converted during the assignment.
Let us consider the situation when the value of arithmetic expression on the
right of sign = has a fractional part and the variable on the left of sign = is of the
Integer or Long data type. During the assignment, the value is transformed
according to the following rules for rounding off:
if the fractional part of the value is equal to 0.5, this value is rounded up
to the even number from two nearest integers;
otherwise, the value is rounded up to the nearest integer.
Because operations \ and Mod are applicable only to integers, the execution
of these operations over numbers with a fractional part begins with the rounding
42
1.8. Arithmetic expression
off the operands to integers according to the formulated rules. The results of
operations \ and Mod are integers.
An operation with one operand is called a unary operation. Among the arith-
metic operations, only the sign change operation (–) is unary. An operation with
two operands (^, *, /, \, Mod, +, – as subtraction) is called a binary operation.
VB includes special functions for converting data types. Two of these func-
tions (Str and Val) were reviewed in Section 1.4; the remaining functions are
listed in Table 3 below.
Sub Functions()
Dim intN As Integer
Dim strN As String
Dim curN As Currency
intN = -15
strN = Str(intN) 'result: strN = "-15"
strN = CStr(intN) 'result: strN = "-15"
intN = 15 '8th operator
strN = Str(intN) '9th operator
'result: strN = " 15"
strN = CStr(intN) '10th operator
'result: strN = "15"
curN = 25.5 '11th operator
43
Chapter 1. Programming in Visual Basic
44
1.9. Mathematical functions. Functions of date and time
Let us start with an analysis of the mathematical functions given in the table
of Appendix 3.
We already used the square root function, Sqr(x), in our first program —
Pythagoras on p. 17.
The argument of trigonometric functions (cosine, sine and tangent) is an
angle in radians, not in degrees.
Function Atn(x) is an inverse trigonometric function, arctan x . The
arctangent returns (into the program) the angle in radians from -π/2 to π/2 whose
tangent is equal to the value of x. Such angle is called the principal angle of
tan x .
The sign function, Sgn(x), returns -1, 0, 1 at x < 0, x = 0, x > 0, respec-
tively.
The Log(x) function is the natural logarithm of x, ln x . According to
the logarithm properties [3], the following expressions are valid for the decimal
logarithm: lg x = ln x / ln 10 = ln x / 2.302585093.
In Appendix 3, in addition to the main mathematical functions of Visual
Basic, the VB operators are given for counting the values of trigonometric func-
tion cot x , of inverse trigonometric functions arcsin x , arccos x and arccot x
and of decimal logarithm lg x .
In addition to the mathematical functions of Appendix 3, let us consider func-
tion Round(x[, n]) intended for rounding off numbers with a fractional part.
As we know, the square brackets separate an optional part of the construct.
In other words, this function of VB has the following two versions:
the Round(x, n) function returns the value of x, rounded up to n deci-
mal places;
the Round(x) function returns the integer obtained by rounding off the
value of x according to the rules formulated on p. 42; this function is identical to
the Round(x, 0) and CInt(x) functions.
Arguments of the mathematical functions are arithmetic expressions.
Assignment operator
45
Chapter 1. Programming in Visual Basic
c = Sqr(a ^ 2 + b ^ 2)
e = b / c * Cos(a) ^ 3 – d
b / c * cache1 – d
into the code window containing the Functions program (p. 43), above the
last line;
2) mark the last line of the program by the breakpoint;
3) click on arrow ► for the program execution up to the breakpoint;
4) make sure that the calculated values of V and W are equal to 33.21 and
1089, respectively;
5) explain these results;
6) click on arrow ► for terminating the program execution.
In addition to the considered functions with one and two arguments, there is
the Rnd function (from “random”) without arguments. This function is intended
for generation of random numbers used for modeling random phenomena. The
simplest random phenomenon can be described as follows: there is a 50 %
chance that the “head” or “tail” will be the result of a coin flip.
The idea of modeling random phenomena is known for a long time. Follow-
ing the advent of the electronic computers, this idea was developed in the 1950s
under the name of the Monte Carlo method.
46
1.9. Mathematical functions. Functions of date and time
The Monte Carlo method is used for modeling financial risks, semiconductor
devices and evolution of stars. It is only a part of the problems demanding
generation of random numbers.
The use of the Rnd function is described in the Excel help system, which
must be started by pressing the F1 key when the VB window is active. The
RandomNumbers program in Section 1.15 and code Listing 6.11 in Section 6.8
are examples of the Rnd function’s usage.
Functions of date and time, Time, Date and Now, are without arguments
too. These functions return the following values of the Date data type: current
time, date and date together with time, respectively. They appeared in program
Century_20 (p. 25). We will encounter these functions of date and time more
than once.
47
Chapter 1. Programming in Visual Basic
Sub Logic1()
Dim x As Integer
Dim y As Integer
Dim blnA As Boolean
x = 5: y = 2
blnA = x > y 'result: blnA = True
blnA = x = y 'result: blnA = False
End Sub
In this program, we see four assignment operators and two logical expres-
sions (x > y and x = y). According to the assignment operator syntax, the logical
expressions are on the right of the assignment sign. The values of the logical
expressions for x = 5 and y = 2 are given in the corresponding comments.
In complicated logical expressions, logical operations are used. We will con-
sider three of them: Not, And, Or.
48
1.10. Logical expression
A B A And B
True True True
True False False
False True False
False False False
A B A Or B
True True True
True False True
False True True
False False False
According to these tables, the And and Or operations have two operands
(A and B), i.e., they are binary operations.
Logical expression A And B is equal to True only in that case when both
operands are equal to True. In all other cases, expression A And B is equal to
False. The And operation is called conjunction or logical multiplication.
Expression A Or B is equal to False only in that case when both operands
are equal to False. In all other cases, expression A Or B is equal to True. The
Or operation is called disjunction or logical addition.
In the presence of several logical operations in a logical expression, the order
of their performance is defined by the following rules of priorities:
1) first of all, operation Not (logical negation) is performed;
2) further, And (logical multiplication);
3) in last turn, Or (logical addition) is performed.
For change of sequence of the operations’ performance, parentheses are used,
as in arithmetic expressions. Parentheses may be also used for readability of
logical expressions.
49
Chapter 1. Programming in Visual Basic
Sub Logic2()
Dim x As Double
Dim y As Double
Dim z As Double
Dim blnA As Boolean
x = 1
y = 2.87
z = 3.12
blnA = (x > y) And (y < z) 'result: blnA = False
blnA = x < y And y < z 'result: blnA = True
blnA = x > y Or y > z 'result: blnA = False
blnA = Not (x < y Or Not y < z)
'result: blnA = False
blnA = Not x > y And x > y 'result: blnA = False
blnA = Not (x > y And x > y) 'result: blnA = True
End Sub
In operator
parentheses are used for readability of logical expressions x > y and y < z.
These parentheses may be omitted.
We advise the reader to verify the correctness of the Logic2 program by
means of the step-by-step execution.
Note that double logical expressions, for example 0 < x <= 1, are inadmissi-
ble in VB. Instead of 0 < x <= 1, we have to write
or
For grasping the material of this and the previous sections, we advise the
reader to write a program allowing to define the values of y, for which
CInt(y), Fix(y), Int(y), Round(y) are equal to each other if y accepts
the following values:
50
1.10. Logical expression
51
Chapter 1. Programming in Visual Basic
Operators of the previous programs are executed by turn. Such programs are
called linear programs.
The GoTo operator is used to change the order of execution of the program
operators. It has the following syntax:
GoTo lbl
In this syntax, the so-called label, lbl, may be one of the following:
a non-negative integer without a sign (0, 1, 2, 3, …);
a sequence of letters, figures and underscores beginning with a letter, for
example, start_53a.
We have to place the lbl label in front of the operator, to which the jump
must be performed (or, that is the same, to which the control must be trans-
ferred). We have to type a colon behind the label.
After executing the operator with lbl in front, the next operator will be exe-
cuted if the labeled operator is not GoTo.
Examples of GoTo usage are given on p. 54: we see two labels in the IT2
program, 2 and LastLine.
If the label is a non-negative integer, this label may be called an operator’s
(line’s) number. For example, operator
in the IT2 program with label 2 in front may be named as operator 2 (line 2).
The GoTo operator is often called the unconditional jump operator. In the
next section, we will consider GoTo as a part of the so-called conditional jump
operator.
52
1.12. Decision-making constructs
Sub IT1()
Dim X As Byte
X = 12 'initial value of X
If (X > 9 And X < 12) Then X = X + 1
X = X + 2
X = X * 2 'final value of X
End Sub
53
Chapter 1. Programming in Visual Basic
According to this construct including GoTo, if the condition is true, the jump is
performed to the operator labeled by lbl.
The program below is an example of using the conditional jump operator.
Sub IT2()
Dim X As Integer
X = 12
2: If X > 9 And X < 12 Then GoTo LastLine
X = X - 2
GoTo 2
LastLine:
End Sub
We advise the reader to make the step-by-step execution of this program and
to explain why the value of X changes so, instead of differently.
The quantity of operators, which must be executed when the condition is true,
may be greater than one. In this case, the following construct is used:
If condition Then
statements
End If
54
1.12. Decision-making constructs
Else) is executed. Further, the jump is performed to the operator following the
If…Then construct, without dependence of what operator was executed earlier,
statement1 or statement2 (if these operators are not GoTo).
The program below is an example of using the last construct.
Sub IT3()
Dim X As Byte
X = 12 'initial value of X
If (X > 9 And X < 12) Then X = X + 3 _
Else X = X + 2
X = X * 2 'final value of X
End Sub
If condition Then
statements1
Else
statements2
End If
If condition1 Then
statements1
ElseIf condition2 Then
statements2
∙ ∙ ∙ ∙
ElseIf conditionN Then
statementsN
[Else
statements]
End If
55
Chapter 1. Programming in Visual Basic
If the first condition is true (that is, logical expression condition1 accepts
True), then block statements1 is executed. If this condition is false, the
second condition (which is behind keyword ElseIf) is checked. If this condi-
tion is true (condition2 = True), then block statements2 is executed,
and so on. If conditionN = True, then block statementsN is executed.
If none of the N conditions is true, then block statements (located below the
Else keyword) is executed.
Further, the jump is performed to the operator following the End If key-
word combination, without dependence of what block was executed earlier,
statements1, statements2, ..., statementsN or statements.
An example of using the last construct is in codes Listings 5.7 and 5.8 of
Section 5.11.
We reviewed several versions of the conditional operator. In addition, let us
consider function
Sub IT4()
Dim intA As Integer, strA As String
intA = 6
strA = IIf(intA Mod 2 = 0, "Even", "Odd")
End Sub
56
1.12. Decision-making constructs
statements2
∙ ∙ ∙ ∙
Case valueN
statementsN
[Case Else
statements]
End Select
Sub Choice()
Dim x As Integer
x = 1
Select Case 2 * x + 1
Case 1
x = x + 1
Case 2, 3, 4
x = 10
Case Else
x = 20
End Select
x = x Mod 3
End Sub
57
Chapter 1. Programming in Visual Basic
1.13. Cycles
To execute repeatedly an operator block, we can use one of three cycle opera-
tors, For…Next, While…Wend and Do…Loop.
The For…Next cycle is used when the number of the block’s executions is
known in advance, i.e., before the first execution of this block. This construct has
the following syntax:
where counter is a variable of numerical data type (p. 24), beginning and
ending are the boundaries of the counter change, growth is the step of this
change; beginning, ending and growth are the cycle parameters.
Let us consider the For…Next cycle at a positive value of growth.
At first, the value of beginning is assigned to the counter variable.
Further, condition counter > ending is checked. If the result is True, the
cycle is completed, at that, block statements is not executed even once.
If the result of checking condition counter > ending is equal to False,
then block statements is executed for the first time. After that, the jump
occurs to the cycle beginning. Further, the counter variable’s value increases
by growth, and condition counter > ending is checked again. If the result
is equal to False, then block statements is executed for the second time,
and so on.
The cycle is completed when the check of condition counter > ending
gives True. In this case, the operator following the cycle is executed.
As an example of the cycle usage, let us consider the following program for
calculating the factorial of number 6:
Sub Factorial1()
Dim I As Byte
Dim F As Long
F = 1
58
1.13. Cycles
For I = 1 To 6 Step 1
F = F * I
Next I
End Sub
Sub Factorial2()
Dim I As Integer
Dim F As Long
F = 1
For I = 6 To 1 Step -1
F = F * I
Next I
End Sub
If the Step keyword is omitted, the step of the counter change is equal to
unity by default.
Arithmetic expressions may be used as the cycle parameters (beginning,
ending and growth). It is important that all variables in these arithmetic
expressions had numerical values before the For…Next cycle work.
As an example of such usage of arithmetic expressions, let us consider the
following 3rd version of the program for calculating 6!:
Sub Factorial3()
Const e As Double = 2.718281828
Dim J As Byte
59
Chapter 1. Programming in Visual Basic
Dim
N As Byte
Dim
F As Long
N =
Round(e)
F =
1
For
J = 1 To N ^ 2 - 3
F = F * J
Next J
End Sub
The Exit For operator is used for immediate exit from the cycle. It is a part
of the simplest conditional operator. The last cycle works as follows.
For each value of the counter variable, after executing the statements1
block, the computer calculates the value of logical expression condition.
If this value is False, the cycle continues to work. Otherwise, the jump is per-
formed to the operator following the cycle construct (without executing block
statements2).
As an example of using the Exit For operator, let us consider the following
4th version of the program for calculating 6!:
Sub Factorial4()
Dim I As Byte
Dim F As Long
F = 1
For I = 1 To 13
F = F * I
If I = 6 Then Exit For
Next I
End Sub
60
1.13. Cycles
The While…Wend cycle is used when the number of the block’s executions
is not known in advance. The syntax of this cycle follows:
While condition
statements
Wend
The While…Wend cycle work begins with calculating the value of logical
expression condition. If condition = False, the cycle is completed, i.e.,
the jump is performed to the operator following the Wend keyword.
If condition = True, block statements is executed. After that, the value
of logical expression condition is calculated again, and so on.
The 5th version of the program for calculating 6! follows:
Sub Factorial5()
Dim I As Byte
Dim F As Long
F = 1
I = 1
While I <= 6
F = F * I
I = I + 1
Wend
End Sub
The Do…Loop cycle, as well as the While…Wend cycle, is used when the
number of the block’s executions is not known in advance. Four versions of this
construct exist.
The first version is the Do While…Loop cycle with the following syntax:
Do While condition
statements
Loop
The Do While…Loop cycle work begins with calculating the value of logi-
cal expression condition. If condition = False, the cycle is completed,
i.e., the jump is performed to the operator following the Loop keyword. If
condition = True, block statements is executed. After that, the value of
logical expression condition is calculated again, and so on.
The Do While…Loop cycle is equivalent to the While…Wend cycle
reviewed above.
61
Chapter 1. Programming in Visual Basic
Sub Factorial6()
Dim I As Byte
Dim F As Long
F = 1
I = 1
Do While I <= 6
F = F * I
I = I + 1
Loop
End Sub
Sub Steps1()
Dim x As Single
Dim h As Single
h = 0.5 'step equals 0.5
x = 44 'initial value of x equals 44
Do While x < 55 'final value of x equals 55
x = x + h 'value of x increases by h
Loop
End Sub
Do Until condition
statements
Loop
The Do Until…Loop cycle work begins with calculating the value of logi-
cal expression condition. If condition = True, the cycle is completed,
i.e., the jump is performed to the operator following the Loop keyword.
If condition = False, block statements is executed. After that, the value
of logical expression condition is calculated again, and so on.
62
1.13. Cycles
The program with the Do Until…Loop cycle for the movement along the x
axis has the following form:
Sub Steps2()
Dim x As Single
Dim h As Single
h = 0.5 'step equals 0.5
x = 44 'initial value of x equals 44
Do Until x >= 55 'final value of x equals 55
x = x + h 'value of x increases by h
Loop
End Sub
Do
statements
Loop While condition
The Do…Loop While cycle work begins with executing operator block
statements. After that, the value of logical expression condition is
calculated. If condition = False, the cycle is completed. Otherwise, block
statements is executed again, and so on.
The program with the Do…Loop While cycle for the movement along the x
axis has the following form:
Sub Steps3()
Dim x As Single
Dim h As Single
h = 0.5 'step equals 0.5
x = 44 'initial value of x equals 44
Do
x = x + h 'value of x increases by h
Loop While x < 55 'final value of x equals 55
End Sub
63
Chapter 1. Programming in Visual Basic
The Do…Loop Until cycle, which is the fourth version of the Do…Loop
construct, has the following syntax:
Do
statements
Loop Until condition
The Do…Loop Until cycle work begins with executing operator block
statements. After that, the value of logical expression condition is
calculated. If condition = True, the cycle is completed. Otherwise, block
statements is executed again, and so on.
The program with the Do…Loop Until cycle for the movement along the x
axis has the following form:
Sub Steps4()
Dim x As Single
Dim h As Single
h = 0.5 'step equals 0.5
x = 44 'initial value of x equals 44
Do
x = x + h 'value of x increases by h
Loop Until x >= 55 'final value of x equals 55
End Sub
During the work of the Do…Loop While and Do…Loop Until cycles,
block statements is executed at least once because the condition of complet-
ing the cycle is checked after the block execution.
All four versions of the Do…Loop cycle can contain the Exit Do operator
intended for immediate exit from the cycle. In the usage, this operator is similar
to the Exit For operator of the For…Next cycle.
For the While…Wend cycle, there is no operator similar to the Exit For
and Exit Do operators.
64
1.14. Manifestation of the error of real numbers’ computer representation
In the last program of the previous section, we will reduce the value of h to
one-fifth. We can expect that the number of repeated executions of operator
x = x + h will increase fivefold as a result and the final value of x will remain
equal to 55. However, it is not so: the final value of x is equal to 55.09983.
In order to verify this assertion, we do the following:
1) enter program
Sub Steps5()
Dim x As Single
Dim h As Single
h = 0.1 'this operator distinguishes
'Steps5 from Steps4
x = 44
Do
x = x + h
Loop Until x >= 55
End Sub
65
Chapter 1. Programming in Visual Basic
Sub Steps6()
Dim x As Single
Dim h As Currency 'this operator distinguishes
'Steps6 from Steps5
h = 0.1
x = 44
Do
x = x + h
Loop Until x >= 55
End Sub
66
1.14. Manifestation of the error of real numbers’ computer representation
67
Chapter 1. Programming in Visual Basic
1.15. Arrays
is equivalent to operator
68
1.15. Arrays
Option Base 1
is equivalent to operator
Sub StaticArrays()
Dim B1(1 To 6) As Byte, S1 As Byte
Dim B2(1 To 6) As Currency, S2 As Currency
Dim B3(1 To 6) As Byte, S3 As Byte
Dim I As Byte
'Determination of first five elements of arrays:
For I = 1 To 5 'first cycle
B1(I) = I 'first power of I
B2(I) = I ^ .333 'cubic root of I
B3(I) = I ^ 3 'I cubed
Next
'Determination of sixth elements of arrays:
S1 = 0
S2 = 0
S3 = 0
For I = 1 To 5 'second cycle
S1 = S1 + B1(I)
S2 = S2 + B2(I)
S3 = S3 + B3(I)
Next
B1(6) = S1
B2(6) = S2
B3(6) = S3
End Sub
69
Chapter 1. Programming in Visual Basic
In this program:
the first cycle is used for determination of the first five elements of arrays
B1, B2 and B3; upon completing the cycle, these elements of the arrays contain
the numerical values, which are equal to the 1st, 1st / 3rd and 3rd powers of I:
B1(1) = 1, B1(2) = 2, …, B1(5) = 5; B2(1) = 1, B2(2) = 1.2596, …,
B2(5) = 1.7091; B3(1) = 1, B3(2) = 8, …, B3(5) = 125;
the second cycle is used for summation of the earlier determined elements
of the arrays; upon completing the cycle, the sums of the first five elements of
arrays B1, B2 and B3 are respectively equal to S1 = 15, S2 = 6.9971 and
S3 = 225;
the remaining operators of the program assign the calculated values of the
sums to the sixth elements of the arrays: B1(6) = 15, B2(6) = 6.9971 and
B3(6) = 225.
It was noted above that one-dimensional and multidimensional arrays exist.
We reviewed one-dimensional arrays, which are similar to rows and columns on
the Excel worksheet and to vectors in mathematics.
For declaration of multidimensional arrays (with several indices), we use
a construct similar to operator Dim for one-dimensional arrays. The difference
consists in that several boundaries are given through a comma.
For example, operators
A(i, j + 1) = 17
D(K) = A(i, 0)
As we see, the reference may be on the left and/or right of the assignment sign.
70
1.15. Arrays
Operator
Sub DynamicArray()
Dim A() As Byte 'declaration of array
Dim M As Integer, N As Integer
M = 3
ReDim A(-5 To M ^ 2) 'specification of boundaries
For N = -5 To M ^ 2
A(N) = N + 30
Next
ReDim A(5) 'specification of boundaries
N = 0
Do
A(N) = N ^ 3
N = N + 1
Loop Until N ^ 2 > 10
End Sub
71
Chapter 1. Programming in Visual Basic
After typing this program in the code window, let us do the following.
1. By clicking, set the blinking cursor on variable A, more precisely, in front
of or behind A. Fulfill operations Debug > Add Watch. The Add Watch window,
containing the variable name in text box Expression, appears.
2. Click on OK. The Watches window, intended for the current visualization,
appears with a line corresponding to the A array.
3. Set the blinking cursor in any place of the program text.
4. Execute the program step-by-step (Fig. 1.11), watching the A array values
by means of the Watches window.
For visualization of the A array values in the Watches window, we must click
on the plus sign in front of A in this window. As a result, plus turns to minus and
the A array values appear below.
We can edit the contents of the Watches window.
Let us admit that we want to watch the value of variable n instead of the A
array values. For this purpose, during the step-by-step program execution
(between presses of the F8 key), we must:
72
1.15. Arrays
1) click on the minus sign in front of A; as a result, the plus sign appears but
the A array values disappear;
2) highlight A by clicking on it (in the Watches window);
3) type n instead of A highlighted;
4) press the Enter key;
5) continue the step-by-step program execution, watching the value of n.
To remove the line, corresponding to the A array, from the Watches window,
we must:
1) highlight this line by clicking on the glasses pictogram;
2) press the Delete key.
To add a line, we must fulfill Debug > Add Watch, and so on.
To close the Watches window, we must click on the little cross in the top
right corner of this window. To open the Watches window, we must fulfill
View > Watch Window.
The ReDim operator can be used for changing the array’s dimension, as in
the following program:
Sub Dimension()
Dim arrA() As Byte
ReDim arrA(1, 1) 'two-dimensional array
arrA(0, 0) = 13: arrA(0, 1) = 14
arrA(1, 0) = 15: arrA(1, 1) = 16
ReDim arrA(1 To 3, 3, 3) 'three-dimensional array
arrA(1, 0, 0) = 17
End Sub
Note that, at repeated execution of the ReDim operator, the array values will
be lost because the ReDim operator nulls all elements of the array.
To keep the array values, we have to insert the Preserve keyword between
ReDim and the array name. As an example, see operators 0, 1 and 2 in the fol-
lowing program:
Sub Conservation1()
Dim J As Integer
0: Dim arrA() As Integer 'declaration of array
1: ReDim arrA(-5 To 1) 'specification of boundaries
For J = -5 To 1
arrA(J) = J ^ 2
Next J
2: ReDim Preserve arrA(-5 To 4)
'specification of boundaries
73
Chapter 1. Programming in Visual Basic
For J = 2 To 4
arrA(J) = J ^ 3
Next J
End Sub
Sub Conservation2()
Dim I As Integer, J As Integer
0: Dim arrA() As Integer 'declaration of array
1: ReDim arrA(2, -5 To 1)
'specification of boundaries
For I = 0 To 2
For J = -5 To 1
arrA(I, J) = (I + 1) * J ^ 2
Next J
Next I
2: ReDim Preserve arrA(2,-5 To 4)
'specification of boundaries
For I = 0 To 2
For J = 2 To 4
arrA(I, J) = (I + 1) * J ^ 3
Next J
Next I
End Sub
We advise the reader to make the step-by-step execution of the last program,
watching the arrA array values by means of the Watches window.
The values of the lower and upper boundaries of any index can be returned to
the program. For this purpose, functions LBound and UBound are respectively
used. We can look the description of these functions in the Excel help system
started by pressing the F1 key when the VB window is active.
74
1.15. Arrays
Function UBound is necessary, for example, when the value of the upper
boundary is unknown and, at the same time, we have to increase this value by
certain number.
As it was already told, advantage of the dynamic array over the static is that
we can free the memory cells, earlier occupied by the dynamic array. Operator
Erase is used for this, as in the following example program:
Sub Memory()
Dim A() As Byte
Dim B() As Byte
ReDim A(8) 'memory for A: 9 + 4 + 20 = 33 bytes
Erase A 'memory for A: 0 bytes
ReDim B(2, 3)
'memory for B: 12 + 8 + 20 = 40 bytes
End Sub
After inputting the Memory program into the code window, let us make the
following:
1) generate the lines corresponding to arrays A and B in the Watches win-
dow, fulfilling Debug > Add Watch twice;
2) click on any place of the program text to set the blinking cursor there;
3) execute the program step-by-step, watching the memory distribution by
means of the Watches window.
For solving a series of mathematical problems, arrays of random numbers are
required. They can be generated by means of the Rnd function (p. 46).
Let us consider the following program:
Sub RandomNumbers()
Dim N As Long
Dim I As Long
Dim S() As Single
N = 20
ReDim S(1 To N)
75
Chapter 1. Programming in Visual Basic
This program calculates 20 random real numbers from 0 to 1 and writes them
into dynamic array S. The Rnd function is being called in cycle For…Next.
Function Rnd is the built-in generator of random real numbers uniformly
distributed on segment [0, 1] : a number, being returned by the Rnd function,
appears in any place of segment [0, 1] with equal probability.
Before a series of the Rnd function calls, the Randomize operator must be
executed for preparing the random-number generator for work.
We advise the reader to execute the RandomNumbers program step-by-
step, watching the S array by means of the Watches window.
Operator Randomize and function Rnd are used in code Listing 6.11
intended for minimization of the multimodal function (Section 6.8).
76
1.16. User-defined procedures
where name is the function name, type is the data type (Appendix 1) of
name, i.e., of the function value, formal_parameters are the parameter
(argument) names listed through a comma, statements is the operator block.
The parameter names can be accompanied by keywords.
Block statements must include at least one assignment operator whose
left-hand side (on the left of sign =) is the function name.
The function call looks like
name([actual_parameters])
77
Chapter 1. Programming in Visual Basic
Sub Program1()
Dim L As Long
Dim W As Double
L = Fact(12)
W = 4.2 + Fact(10) / 2
End Sub
The first group of operators is program Program1; the second group is the
declaration of function Fact. They are in one or different modules of the same
Excel workbook, i.e., we can type the program and the function declaration in
one or different code windows.
The Fact function calculates N!, i.e., factorial of natural number N, which is
the formal parameter.
We see two calls of the Fact function in the program, with 12 and 10 as the
actual parameter.
1. The Fact function call is located in the right-hand side of assignment
operator
L = Fact(12)
As a result of the operator execution, the Fact function value (that is, the value
returned by the Fact function into the program when N is equal to 12) is
assigned to the L variable.
78
1.16. User-defined procedures
4.2 + Fact(10) / 2
Sub name([formal_parameters])
statements
End Sub
Call name([actual_parameters])
name [actual_parameters]
Sub Program2()
Dim aa As Single, bb As Single
Dim cc1 As Single, cc2 As Single, cc3 As Single
aa = 3
bb = 4
Call Hypotenuse(aa, bb, cc1)
'1st call of subroutine
Call Hypotenuse(3, 4, cc2)
'2nd call of subroutine
Hypotenuse aa, bb, cc3
'3rd call of subroutine
End Sub
79
Chapter 1. Programming in Visual Basic
The first group of operators is program Program2, the second group is the
declaration of subroutine Hypotenuse for calculating the length of the hypote-
nuse of a right-angled triangle. They are located in one or different modules.
We see three operators of calling the Hypotenuse subroutine in program
Program2, and two of them contain the Call keyword.
Formal parameters A and B (in the subroutine declaration) are the input pa-
rameters, lengths of the legs. The ByVal keyword in front of A and B in the first
line of the subroutine declaration (i.e., in the header of the operator block) means
that these parameters must be passed by value (when calling Hypotenuse). In
this case, the values of parameters A and B (3 and 4, respectively) are transferred
to the Hypotenuse subroutine at all three calls.
Formal parameter C is the output parameter, i.e., the hypotenuse length. The
ByRef keyword in front of C means that this parameter must be passed by
reference (when calling Hypotenuse). In this case, the address of the memory
cell, corresponding to variable cc1 (at the first call), cc2 (at the second call)
or cc3 (at the third call), is transferred to the Hypotenuse subroutine.
Keyword ByRef may be omitted.
In the code under consideration, the parameters of the Hypotenuse subroutine
are simple variables (not arrays). If the parameters are arrays, both input and
output parameters must be passed by reference.
Let us consider the following code located in one module:
Dim N1 As Integer
Sub Program3()
Dim xx(50) As Double
Dim yy(50) As Double
Dim i As Integer
N1 = 3
For i = N1 To 30
xx(i) = 0.1 * i
Next i
Call XSINX(30, xx, yy) 'call of subroutine
End Sub
80
1.16. User-defined procedures
Dim j As Integer
For j = N1 To N2
F(j) = X(j) * Sin(X(j))
Next j
End Sub
Private N1 As Integer
All that was said about variables also concerns the user-defined constants, but
the constant’s value, naturally, cannot be changed.
If the declaration of the XSINX subroutine is located in the separate module,
the first line of the last code should be as follows:
Public N1 As Integer
81
Chapter 1. Programming in Visual Basic
Sub Program4()
Dim bytA As Byte, bytB As Byte
Dim intC As Integer
bytA = 5
bytB = 10
intC = Apt(bytA, bytB)
'result: bytB = 6, intC = 625
bytB = 10
intC = Apt(bytA) 'result: bytB = 10, intC = 625
End Sub
82
1.16. User-defined procedures
Sub Program5()
Dim bytA As Byte, bytB As Byte, bytC As Byte
bytA = 5: bytB = 2
Call Ept(bytA, bytC, 5 * bytB) 'result: bytC = 15
Call Ept(bytA, bytC) 'result: bytC = 8
End Sub
In this code:
the b parameter of the Ept subroutine is optional;
if the call of Ept contains only two actual parameters, b = 3 is used when
executing operator c = a + b.
We advise the reader to make the step-by-step execution of the Program5
program, watching the value of bytC.
Operators
Exit Sub
Exit Function
are intended for immediate terminating the procedure execution. The first opera-
tor should be in the subroutine declaration, the second — in the function declara-
tion. At their execution, the jump is being performed to the same point, as upon
the normal terminating the procedure execution.
83
Chapter 1. Programming in Visual Basic
The programs in this section use only one user-defined procedure; for exam-
ple, program Program1 uses only the Fact function. However, several user-
defined procedures may be used by one program.
According to the computer terminology, as a program, we can consider the
program itself (the main subroutine) together with the declarations of the user-
defined procedures (used by the program) and/or together with the general decla-
rations area. For example, program Program3 together with operator
Dim N1 As Integer
can also be called program Program3. The following can also be called pro-
gram Program3: the program itself, the XSINX subroutine declaration and the
general declarations area. Sometimes term “program” is used in the extended
sense, which is equivalent to “code”.
84
1.17. Built-in procedures. Usage of standard windows
85
Chapter 1. Programming in Visual Basic
7: MsgBox s
End Sub
2. Let us run the Pythagoras1 program. The window appears (Fig. 1.12),
offering to input the length of the first leg of a right-angled triangle. Let us put,
for example, 400 (without inverted commas) into the text box of this window by
means of the keyboard and click on the OK button.
3. The window appears (Fig. 1.13), offering to input the length of the second
leg. Let us put, for example, 300 and click on OK.
Fig. 1.13. The second window for inputting the source data
4. The window appears (Fig. 1.14), containing the hypotenuse length calcu-
lated. Let us click on the OK button to close this window and terminate the pro-
gram execution.
86
1.17. Built-in procedures. Usage of standard windows
Call MsgBox(s)
The calls of built-in procedures InputBox and MsgBox have only one
parameter (of the String data type), which is obligatory. However, these pro-
cedures also have optional parameters, whose appointment may be looked in the
Excel help system started by pressing the F1 key when the VB window is active.
Before pressing this key, we recommend to locate the blinking cursor on the
required word (InputBox or MsgBox) in the code window containing program
Pythagoras1.
In the Excel help system, the MsgBox procedure is termed as a function,
instead of a subroutine, because the call of MsgBox may be a part of arithmetic
87
Chapter 1. Programming in Visual Basic
expressions. In this case, MsgBox returns (into the program) the integer value
depending on the button, on which the user clicked. In the example below, we
will consider using the MsgBox procedure as a function.
For calculating the area of a right-angled triangle by the Pythagoras1
program, we replace operator 7 by three operators labeled by 7, 8 and 9. The
following program is the result:
Sub Pythagoras2()
Dim a As Single
Dim b As Single
Dim c As Single
Dim s As String
1: s = InputBox( _
"Enter length of the first leg and click OK")
2: a = Val(s)
3: s = InputBox( _
"Enter length of the second leg and click OK")
4: b = Val(s)
5: c = Sqr(a ^ 2 + b ^ 2) 'according to Pythagoras
6: s = Str(c)
7: Dim Ret As Integer
8: Ret = MsgBox(s, vbYesNo, _
"Do you want to calculate area?")
9: If Ret = vbYes Then MsgBox Str(a * b / 2)
End Sub
If MsgBox(s, vbYesNo, _
"Do you want to calculate area?") = vbYes _
Then MsgBox Str(a * b / 2)
This also gives the results shown in Fig. 1.15 and 1.16.
88
1.17. Built-in procedures. Usage of standard windows
89
Chapter 1. Programming in Visual Basic
1.18. Records
Type struct
field1 As type1
field2 As type2
∙ ∙ ∙ ∙ ∙
fieldN As typeN
End Type
where struct is a name of the record, field1, field2, …, fieldN are the
field names, type1, type2, …, typeN are data types (Appendix 1) for the
corresponding fields.
The record creation operator must be placed in the general declarations area
of the program, which uses this record.
For example, we have to work up results of a university session, where the
following three subjects were evaluated: physics, mathematics and informatics.
In this case, the following fields are necessary:
1) name of the student;
2) number of the test book;
3) mark in physics;
4) mark in mathematics;
5) mark in informatics.
Let the name of the record be Session, and let the field names be Name,
Number, Physics, Math and Inform. In this case, the record creation opera-
tor has the following form:
Type Session
Name As String
Number As Long
90
1.18. Records
Physics As Byte
Math As Byte
Inform As Byte
End Type
To get access to the created record (by name struct), we have to declare
one or several variables in the program by means of the Dim operator, in the
same way as we declared variables in Section 1.3.
The declaration operator has the following syntax:
where variable is the variable name, struct is the variable’s data type.
For example, operator
declares variables (records) Sess and BestSess of the Session data type.
For the reference to the record field, we use the variable and field names
separated by a point.
For example, assignment operator
contains the reference in the left-hand side. As a result of the operator execution,
string
"Maksim Zakharkin"
is assigned to the Name field of the Sess variable (of type Session).
For filling the fields, it is convenient to use the With operator, which has the
following syntax:
With variable
.field1 = expression1
.field2 = expression2
∙ ∙ ∙ ∙ ∙ ∙ ∙
.fieldN = expressionN
End With
91
Chapter 1. Programming in Visual Basic
For example:
With Sess
.Name = "Maksim Zakharkin"
.Number = 02237
.Physics = 4
.Math = 5
.Inform = 5
End With
The assignment operator can be applied both to fields and to entire records,
as in the following examples:
BestSess.Number = Sess.Number
BestSess = Sess
Arrays of records may be used. For example, it is natural to store the marks
obtained by students of group E13 in array SessE13. If this array of records is
static, it is declared as follows:
For example, let us consider the following code for calculating distance
between Tushino and Ostankino on the Moscow map.
Listing 1.4
Type Point
Name As String
x As Single
y As Single
End Type
Sub TushinoOstankino()
Dim P() As Point
ReDim P(0 To 1)
With P(0)
.Name = "Tushino"
.x = 17.6
.y = 29.7
End With
92
1.18. Records
With P(1)
.Name = "Ostankino"
.x = 44.1
.y = 37.5
End With
MsgBox Str(Distance(P())) 'output of 27.62408
End Sub
Code Listing 1.4 includes the operator creating the Point record, program
TushinoOstankino and the Distance function. This code has the follow-
ing peculiarities:
P is the dynamic array of records of the Point data type;
the Distance function argument is the array of records of type Point.
To understand the work of program TushinoOstankino, we advise the
reader to execute it step-by-step, watching the P array in window Watches.
Before the first press of the F8 key, the blinking cursor should be located in the
TushinoOstankino program, not in the operator creating the Point record
and not in the Distance function.
93
Chapter 1. Programming in Visual Basic
The string is not only a pair of quotation marks "" and a sequence of charac-
ters enclosed in quotes (p. 27), but also a variable of the String data type,
declared by means of the String keyword. For example, in operator block
Dim A As String
Dim B As String * 15
A = "Informatics"
B = "Informatics"
A = "Informatics"
94
1.19. Work with strings
Sub Strings1()
Dim strA As String, strB As String, strC As String
strA = "String ": strB = "variable"
strC = strA & strB
'result: strC = "String variable"
strC = "String " + strB
'result: strC = "String variable"
End Sub
95
Chapter 1. Programming in Visual Basic
Sub Strings2()
Dim strA As String, strB As String
strA = " String variable "
strB = Trim(strA)
'result: strB = "String variable"
strB = LTrim(strA)
'result: strB = "String variable "
strB = RTrim(strA)
'result: strB = " String variable"
End Sub
Sub Strings3()
Dim strA As String, curB As Currency
Dim strC As String
strA = "X = "
curB = 45.77
strC = strA & CStr(curB)
'result: strC = "X = 45.77"
curB = Val("45.77 = X") 'result: curB = 45.77
curB = Val(strC) 'result: curB = 0
strC = "String" & Space(3) & "variable"
'result: strC = "String variable"
End Sub
Sub Strings4()
Dim strA As String, strB As String
strA = "Pavel Ivanov"
strB = UCase(strA) 'result: strB = "PAVEL IVANOV"
strB = LCase(strA) 'result: strB = "pavel ivanov"
End Sub
96
1.19. Work with strings
Sub Strings5()
Dim strA As String
Dim strB As String
strA = "Pavel Ivanov"
strB = Replace(strA, "Ivanov", "Gusev")
'result: strB = "Pavel Gusev"
End Sub
Sub Strings6()
Dim strA As String
Dim intA As Integer
strA = "String variable"
intA = Len(strA) 'result: intA = 15
End Sub
Left(string, quantity)
Right(string, quantity)
These functions return the string containing the specified quantity of charac-
ters of the beginning and end of string, respectively.
The call of function Mid follows:
97
Chapter 1. Programming in Visual Basic
Functions Left, Right and Mid are used in the following program:
Sub Strings7()
Dim strA As String
Dim strB As String
strA = "My string variable"
strB = Left("My string variable", 9)
'result: strB = "My string"
strB = Right(strA, 8) 'result: strB = "variable"
strB = Mid(strA, 4, 6) 'result: strB = "string"
strB = Mid(strA, 11) 'result: strB = "variable"
End Sub
Let us consider an example of using the compound string in the call of the
MsgBox procedure.
1. In Listing 1.4, we replace operator MsgBox Str(Distance(P()))
on p. 93 by the following operator block:
Dim L As Single
Dim S As String
Dim M As Single
L = Distance(P())
S = InputBox("Enter scale and click OK")
'input of scale, Fig. 1.17
M = Val(S)
L = M * L
MsgBox "Distance from " & P(0).Name & " to " & _
P(1).Name & vbCrLf & "equals" & Str(L) & " km"
'output of distance, Fig. 1.18
98
1.19. Work with strings
Because of using the vbCrLf constant, we see two lines in the resulting
window (Fig. 1.18). The vbCrLf constant can be replaced by association
vbCr & vbLf of built-in constants “return” vbCr (from “Carriage return”) and
“new line” vbLf (from “Linefeed”).
The TimeValue function is useful, which converts time from the String
data type to the Date data type. As an example of using this function, let us
consider the following program:
Sub TV()
Dim dTime1 As Date
Dim dTime2 As Date
Dim dTime3 As Date
dTime1 = #2:30:45# + TimeValue("00:15:00")
'1st assignment operator
'result: dTime1 = 2:45:45
99
Chapter 1. Programming in Visual Basic
Because of executing the 2nd assignment operator, the dTime2 variable has
a value, which is equal to the current date and time plus 25 minutes. Because of
executing the 3rd assignment operator, dTime3 is equal to the current time plus
10 seconds.
In Listing 2.10 on p. 170, we will use the Format function intended for
converting a value to a string of the given form. To see the full information on
this function, we must press the F1 key when the blinking cursor is located on
Format in the code window.
100
1.20. Work with text files
A file is an area on a hard disk, compact disk, USB flash drive (UFD) or any
other medium that:
contains single-type information;
has a name.
When working with files, we will use operations for reading information
from a file and writing information into a file.
Several types of files exist; we will consider text files. The contents of such
file are lines of characters with a combination of characters “return” and “new
line” at the end of each line.
For viewing text files, we will use the Notepad editor. At its window, we will
not see characters “return” and “new line”.
To start working with a text file, operator Open is used for opening this file.
This operator has the following syntax:
In this construct, name is the file full name, i.e., the file name together with its
path (in the file system of Windows) and extension, number is the file number,
purpose is keyword Input, Output or Append (from “appending”).
The last three keywords have the following sense:
Input means that the file must be opened for reading information from
this file;
Output — the file must be opened for writing information into it;
Append — the file must be opened for adding information into it.
As the file number, we recommend to use the number variable of the
Integer data type whose value is the result of executing the following assign-
ment operator:
number = FreeFile
where FreeFile is the built-in function that returns (into the program) the free
file number.
101
Chapter 1. Programming in Visual Basic
The last assignment operator must be placed above the Open operator, more
precisely, it must be executed before the Open operator.
After finishing the work with the file, it must be closed by the Close opera-
tor as follows:
Close number
For addition of new lines into the file, operator Print is used, which has the
following syntax:
This operator reads the next line from the file, at that, this line (without “return”
and “new line” at the end) is assigned to variable of the String data type.
2. Extracting information by means of built-in function
Input(quantity, number)
This function returns (into the program) the string, which contains the subse-
quent characters from the file. The quantity of these characters is specified by
quantity.
In programs Creation and Addition, given below, we will use the re-
viewed operators and built-in functions intended for work with text files. Using
these programs as examples, we will also consider other useful operators and
functions.
102
1.20. Work with text files
103
Chapter 1. Programming in Visual Basic
In operators 1, 2 and 3, usr is the computer user name. Before the program
execution, the reader should type his concrete user name instead of usr in these
operators.
During the program execution, operator
MkDir("c:\Users\usr\texts")
creates folder texts inside folder usr; MkDir is the abbreviation of “make
directory”.
The built-in LOF function returns into the program the quantity of characters
in the file, at that, characters “return” and “new line”, which are at the end of
each line, are taken into consideration. The argument of this function is the file
number; LOF is the abbreviation of “length of file”.
The argument of the built-in EOF function is the file number too. This func-
tion, figuring in the condition of the Do Until…Loop cycle termination, returns
(into the program) True at achievement of the file end. The function name is the
abbreviation of “end of file”.
The MsgBox procedure is intended for depicting the string, which is its
parameter, on the display screen. Two calls of MsgBox are in the Creation
program, therefore, two windows, represented in Fig. 1.19 and 1.20, appear
during the program execution.
After termination of the program execution, files a.txt and b.txt have
the following contents.
104
1.20. Work with text files
Fig. 1.19
Fig. 1.20
File a.txt:
File b.txt:
We advise the reader to look through the contents of files a.txt and
b.txt by using the Notepad editor to be convinced of the correctness of the
program work.
Before restarting the Creation program, the MkDir operator of creating
the texts folder must be omitted, for example, by means of an apostrophe.
105
Chapter 1. Programming in Visual Basic
The liquidation of files a.txt and b.txt and folder texts may be
required at the end of the program execution. For this purpose, the following
operators are used:
Kill(FName1)
Kill(FName2)
RmDir("c:\Users\usr\texts")
The Shell function (operator 0) is intended for running any executable file
whose name has extension .exe. The first argument of the Shell function is the
full name of the executable file (here, the full name must be without spaces). The
second argument, which may be omitted, defines the style of the window being
a result of calling the Shell function.
To see the full information on the Shell function, we must press the F1 key
when the blinking cursor is located on Shell in the code window.
106
1.20. Work with text files
We will run the Addition program after the execution of the Creation
program (without the operators liquidating the files and folder).
The window, shown in Fig. 1.21, appears during the Addition program
execution. After clicking on OK in this window, operator 0 is executed, which
starts the Notepad editor (Fig. 1.22), and then operator End Sub is executed, i.e.,
the Addition program is terminated.
Fig. 1.21
107
Chapter 1. Programming in Visual Basic
If a file is opened for adding information (by using keyword Append), this
file may not exist. In this case, the file is created. If a file is opened for reading
information (by using keyword Input), this file, naturally, should exist.
To see file names with extension in Windows Explorer, we must fulfill the
following:
1) in Windows Explorer, open the folder, which contains files of interest;
2) on the menu bar of Windows Explorer, fulfill Organize > Folder and
search options;
3) in open window Folder Options, activate tab View;
4) in list Advanced settings, turn off option Hide extensions for known file
types;
5) successively click on buttons Apply and OK.
To expand the chosen operation mode of Windows Explorer to all folders, we
must click on button Apply to Folders before clicking on the Apply button. In
open window Folder Views, we must click on the Yes button.
We advise the reader to write a program for creating a text file including
n 1 lines of the following form:
f( xi ) fi ,
where xi , fi are the values of argument and function, 0 i n; a x0 < x1 <
x 2 < ... < xn 2
< xn 1
< xn b . Function f (x) and corresponding values of
a and b from Appendix 4 must be used.
The constructs of Visual Basic considered above can be used for solving
sufficiently complicated tasks, two of which will be formulated in the next
section.
108
1.21. Matrix terminology. Formulation of demonstration tasks
In the previous sections, we were solving the task of calculating the hypote-
nuse length. However, this task is very simple, and it is impossible to show all
possibilities of Visual Basic on it. Therefore, we will also solve two tasks of
transposing a numerical matrix, relative to the main and auxiliary diagonals. Let
us formalize the concept of matrix transposition.
Let A be a matrix containing m rows and n columns, B be a matrix containing
n rows and m columns:
a11 a12 ... a1 j ... a1n b11 b12 ... b1i ... b1m
a21 a22 ... a2 j ... a2 n b21 b22 ... b2i ... b2 m
. . . . . . . . . . . .
A , B .
ai1 ai 2 ... aij ... ain b j1 b j 2 ... b ji ... b jm
. . . . . . . . . . . .
am1 am 2 ... amj ... amn bn1 bn 2 ... bni ... bnm
109
Chapter 1. Programming in Visual Basic
Let us notice the following obvious fact: when transposing the matrix relative
to the main diagonal, its rows and columns interchange their positions.
If m = n, matrix A is called a square matrix. In this case, elements a ii are
located on the main diagonal, elements ai , m 1 i
are located on the auxiliary
diagonal, 1 ≤ i ≤ m.
When transposing square matrix A relative to the main (auxiliary) diagonal,
the mirror reflection of A relatively the main (auxiliary) diagonal takes place.
Further, we will use the following terms and definitions.
The A matrix, containing m rows and n columns, is named as “the A matrix
of size m × n” or “the A matrix m × n”. The matrix, containing one column or one
row, is called a vector.
The product of the A matrix m × n and the C matrix n × s is the AC matrix
m × s, which is a result of the scalar multiplication of the rows of A and the
columns of C, namely:
a11c11 ... a1n cn1 a11c12 ... a1n cn 2 ... a11c1s ... a1n cns
a21c11 ... a2 n cn1 a21c12 ... a2 n cn 2 ... a21c1s ... a2 n cns
.
... ... ... ...
am1c11 ... amncn1 am1c12 ... amncn 2 ... am1c1s ... amncns
110
1.22. Program for transposing a matrix relative to its auxiliary diagonal
The program for solving one of the two tasks formulated in the previous sec-
tion is given below. This program uses file a.txt with the source data (values
of m and n and matrix A) and creates file b.txt with the result (the B matrix).
Listing 1.7
Sub TRANSPA()
Dim FNameA As String, FNameB As String
Dim FNum As Integer
Dim strC As String, strD As String, strE As String
Dim m As Integer, n As Integer
Dim i As Integer, j As Integer
Dim k As Integer, l As Integer
Dim A() As Double, B() As Double
1: FNameA = _
"c:\Users\usr\texts\a.txt"
2: FNameB = _
"c:\Users\usr\texts\b.txt"
3: FNum = FreeFile
'Opening file a.txt:
4: Open FNameA For Input As FNum
'Reading values of m and n from file a.txt:
5: Line Input #FNum, strC
6: strC = Mid(strC, 3)
7: m = Val(strC)
8: Line Input #FNum, strC
9: strC = Mid(strC, 3)
10: n = Val(strC)
'Setting size of matrices:
11: ReDim A(1 To m, 1 To n)
12: ReDim B(1 To n, 1 To m)
'Reading matrix A from file a.txt:
13: For i = 1 To m
14: Line Input #FNum, strC
111
Chapter 1. Programming in Visual Basic
15: j = 0
16: strD = ""
'string "" is not equal to string " "
17: l = Len(strC)
18: For k = 1 To l
19: strE = Mid(strC, k, 1)
20: If strE <> " " Then strD = strD & strE
21: If strE = " " Or k = l Then
22: j = j + 1
23: A(i, j) = Val(strD)
24: strD = ""
25: End If
26: Next k
27: Next i
'Closing file a.txt:
28: Close FNum
29: FNum = FreeFile
'Opening file b.txt:
30: Open FNameB For Output As FNum
'Forming matrix B, its writing into file b.txt:
31: For j = 1 To n
32: strC = ""
33: For i = 1 To m
34: B(j, i) = A(m + 1 - i, n + 1 - j)
35: strC = strC & Str(B(j, i)) & " "
36: Next i
37: Print #FNum, strC
38: Next j
'Closing file b.txt:
39: Close FNum
End Sub
c:\Users\usr\texts\a.txt
112
1.22. Program for transposing a matrix relative to its auxiliary diagonal
contains the source data, i.e., values of m and n and matrix A. This file may be
created by means of the Notepad editor whose window is represented in
Fig. 1.23.
For starting the execution, we can use one of the following two ways:
clicking on arrow ► in the VB window;
fulfilling the following operations in the Excel window: Developer (or
View) > Macros > line TRANSPA > Run.
It is possible to appoint a combination of keys starting the program execu-
tion. For that, being in the Excel window, we fulfill operations Developer
(or View) > Macros > line TRANSPA > Options. In open window Macro
Options, we fulfill the following:
appoint the startup key combination, for example, Ctrl + t;
click on the OK button;
close the window by clicking on the little cross in the top right corner.
After that, the simultaneous press of the Ctrl and t keys runs the TRANSPA
program.
The result of the TRANSPA program execution is matrix B, which is in file
c:\Users\usr\texts\b.txt
113
Chapter 1. Programming in Visual Basic
clicking on the Excel button at the left end of the standard toolbar in the
VB window;
simultaneous pressing the Alt and F11 keys;
rolling the VB window down by means of the underscore button in the
top right corner;
clicking on the Excel button on the taskbar of Windows Desktop.
For returning to the VB window from the Excel window, we should fulfill
Developer (or View) > Macros > line TRANSPA > Edit. As a result, the VB win-
dow with the TRANSPA program text in the code window appears. Further, we
can correct the program, for example, change names of files with the source data
and for the calculation result.
If we click on button Step Into (instead of button Edit), the VB window will
also be opened. Further, the step-by-step execution of the TRANSPA program
(by means of the F8 key) is possible.
Other ways of transition from the Excel window to the VB window follow:
pressing Alt + F11;
rolling the Excel window down by means of the underscore button;
clicking on the VBA button on the taskbar of Windows Desktop.
The TRANSPA program text almost coincides with the text of the program,
which will be reviewed in the next section. Therefore, the TRANSPA program
will still be required.
For further usage of the TRANSPA program, we have to save it on the com-
puter’s hard disk by fulfilling the following operations similar to the operations
described on p. 18:
1) in the Excel window, File > Save As > Browse;
2) in the Save As window, choose a folder intended for saving the Excel
workbook, for example, c:\Users\usr;
114
1.22. Program for transposing a matrix relative to its auxiliary diagonal
115
Chapter 1. Programming in Visual Basic
As the program user interface, the form is sometimes convenient. For creat-
ing this rectangle with text boxes, buttons and other control elements, Form
Designer exists in Visual Basic Environment.
Let us create the form for the program intended for calculating the length of
the hypotenuse of a right-angled triangle.
The following control elements are suitable for the form:
place for displaying the calculation result;
text box for inputting (into the program) the length of the first leg;
text box for inputting the length of the second leg;
button for starting the calculation.
Let Book1 be the name of the active Excel workbook. Developing the pro-
gram (project) with the form begins with the following sequence of operations
for inserting the form into the active Excel workbook (instead of inserting the
module).
1. In the Excel window, fulfill Developer > Visual Basic in area Code.
As a result, the VB window (Fig. 1.1) containing the project explorer window
and the properties window appears.
In the absence of the properties window, we can open it by fulfilling View >
Properties Window.
2. In the project explorer window, highlight line VBAProject (Book1) by
clicking on it.
3. Fulfill Insert > UserForm.
As a result, the following features appear (Fig. 1.25):
blank form UserForm1, a rectangle with points;
line UserForm1 in the project explorer window;
the Toolbox window, containing the control elements.
If the last window is not displayed, for displaying it, we must click on the
form and then fulfill View > Toolbox.
The properties window “is tied” to the form because this element is selected
by the frame with 8 markers (five black and three white, Fig. 1.25).
To change the width of the UserForm1 form, we have to drag the form’s right
border by using the mouse, having seized the white marker in the center of this
116
1.23. User-defined forms
border. Thus, the value of the Width property (in the properties window) also
changes.
Expression “to seize a point” means the following: to place the mouse pointer
on this point, and then to press the left button on the mouse.
The value of property Width (that is, the form width) can also be set in the
properties window.
Similarly, we can change the height of the UserForm1 form (property
Height).
After clicking on property Caption (in the properties window), we will
change it to the following: My first form.
The Toolbox window (Fig. 1.25) contains pictograms of the control elements,
which can be simply used in the project. We will use the following four ele-
ments: Label, TextBox, CommandButton and CheckBox. To see the element
name, we have to place the mouse pointer on this element in Toolbox.
To insert an element into the form and to edit this element, we fulfill the
following operations.
117
Chapter 1. Programming in Visual Basic
118
1.23. User-defined forms
119
Chapter 1. Programming in Visual Basic
Similarly, we can insert the text box into the form. For that, the TextBox
element is used.
We will insert two text boxes (Fig. 1.28), with names TextBoxA and
TextBoxB. On the left of the text boxes, we will create inscriptions a and b by
using the Label element.
To insert the button into the form, we fulfill the following.
1. Click on the CommandButton element, which is in the Toolbox window.
2. Depict the button in the form.
3. Set the following properties of this button.
Caption: Account
Name: ComButCalc
4. Remove the button selection by clicking on area outside its limits.
The development of the form by means of Form Designer is completed. Now
we have to develop the program.
Let us click twice on the Account button, which is in the UserForm1 form.
At that, there appears the code window (corresponding to the form) with the
blank of the program, being started by clicking on the Account button.
120
1.23. User-defined forms
The following first and last lines of the program are generated automatically:
End Sub
121
Chapter 1. Programming in Visual Basic
Further, the calculation may be repeated for other source data, i.e., other
lengths of the triangle’s legs. Upon termination of the series of calculations, we
have to close the form by clicking on the little cross in the top right corner
(Fig. 1.29).
We can simplify the ComButCalc_Click program as follows:
122
1.23. User-defined forms
In the previous section, we developed the TRANSPA program, Listing 1.7, for
transposing a number matrix relative to its auxiliary diagonal. This program is
inconvenient to use because names of files are a part of the program text (see
operators 1 and 2). To eliminate this drawback, we will add the form, already
designed, to the TRANSPA program. In this case, the form elements have the
following sense (from top to down, Fig. 1.28):
place for displaying messages;
text box for inputting the full name of the source data file;
text box for inputting the full name of the result file;
button for starting the calculation.
The basis of the new ComButCalc_Click program is the TRANSPA pro-
gram text, which is in the BookTRANSPA workbook. To gain access to this text,
we fulfill the following (p. 18):
1) open the BookTRANSPA workbook with Excel, for example, by means
of the context menu;
2) go to Visual Basic Environment in the standard way;
3) open the code window with the TRANSPA program text by clicking twice
on the corresponding module name in the project explorer window.
The TRANSPA program text is also contained in file Listing_1_07.txt of the
enclosed CD.
By using the TRANSPA program text, Listing 1.7, we will transform the
ComButCalc_Click program developed above to the following view by
means of Windows Clipboard.
123
Chapter 1. Programming in Visual Basic
124
1.23. User-defined forms
c:\Users\usr\texts\a.txt
c:\Users\usr\texts\b.txt
into text boxes a and b, respectively, and clicking on button Account (usr is the
user name in these two full names).
Further, the calculation may be repeated for other names of the files and for
other contents of the source data file. Upon termination of the series of calcula-
tions, we have to close the form, depicted in Fig. 1.30, by clicking on the little
cross in the top right corner.
The source data file, which contains values of m and n and matrix A, can be
created and/or edited by using the Notepad editor. We can view the calculation
result by means of the same editor. Fig. 1.23 and 1.24 show the Notepad window
with the source data and calculation result.
We can use element TextBox not only for input of information but also for
output. In this case, property Text of the corresponding TextBox element (for
example, property TextBox3.Text) must be in the left-hand side of the assign-
ment operator.
We advise the reader to modify the form and the text of the last program so
that "Account is terminated. Input..." is being put into the text box of the form.
We learned how to use the following three elements of the Toolbox window:
Label, TextBox and CommandButton. Let us also consider element CheckBox,
which is used in the following cases:
an option should either be turned on or turned off;
one of two alternatives must be chosen.
125
Chapter 1. Programming in Visual Basic
In the form, the CheckBox element looks like a little square field. At the click
on this field, the check (tick) mark appears in it; at the repeated click, the check
mark disappears.
Property Value of element CheckBox has value True or False as follows:
True when the check mark is present in the field;
False when the check mark is absent.
Let us expand the form, depicted in Fig. 1.28, by the CheckBox element
placed on the left of the button and return to the program, which calculates the
hypotenuse length.
The new version of the ComButCalc_Click program (p. 121) follows:
126
1.23. User-defined forms
127
Chapter 1. Programming in Visual Basic
128
1.24. Digression. Developing programs with the form in Microsoft Visual Studio
The programs, which were reviewed above and will be reviewed below, have
the following drawback: we must equip our computer with tabular processor
Excel for calculations by means of these programs. If we want to execute a pro-
gram without using Excel, this program should be developed in Visual Basic
Environment, which is not a part of Microsoft Office. Let us consider singulari-
ties of developing the program (project) with the form in Visual Basic Environ-
ment, which is a part of package Microsoft Visual Studio 2010.
Microsoft Visual Studio 2010 is installed on the computer in the standard
way. To start Visual Studio, we fulfill the following operations on Windows
Desktop: Start > All Programs > Microsoft Visual Studio 2010 > Microsoft
Visual Studio 2010. The Start Page window is the result.
For setting the necessary operation mode of Visual Studio, we must fulfill the
following operations:
1) click on the New Project hyperlink;
2) in the left area of the open New Project window, click on the plus sign
against Other Languages;
3) in the open list, click on the plus sign against Visual Basic;
4) in the open list, click on line Windows;
5) in the list of the central area of the New Project window, click on line
Windows Forms Application.
The necessary operation mode of Visual Studio is the result. The following
information in the right area of the New Project window speaks about it:
A project for creating an application with a Windows user interface.
Further, the project name and the folder, intended for the project, must be
given by means of text boxes Name and Location. By default, the project and
folder have the same name, WindowsApplication1 (the digit in the name may be
different).
After clicking on the OK button, the window of Visual Basic Environment
is displayed. Blank form Form1 is a part of this window. Fig. 1.33 shows the
window after fulfilling View > Toolbox. To open the properties window, we must
fulfill the following operations: View > Other Windows > Properties Window.
The properties window (Fig. 1.34) appears in place of the Toolbox window.
129
Chapter 1. Programming in Visual Basic
130
1.24. Digression. Developing programs with the form in Microsoft Visual Studio
a =
Val(s)
s =
TextBoxB.Text
b =
Val(s)
c =
Math.Sqrt(a ^ 2 + b ^ 2)
'according to Pythagoras
s = Str(c)
LabelMessage.Text = "c=" & s
End Sub
End Class
The beginning and end of the program were generated automatically when
we clicked twice on the button inserted into the form.
The project contains several files and folders. By default, it is located in the
folder with the following full name:
c:\Users\usr\WindowsApplication1
131
Chapter 1. Programming in Visual Basic
To save the current state of the project, we must fulfill File > Save. For
returning to the project, we can use one of the following two ways:
the double click on the WindowsApplication1.vbproj file in the project
folder;
the click on the WindowsApplication1 hyperlink in area Recent Projects
of the Start Page window of Visual Studio.
When we execute the program during its development, the debug version of
the program executable file is created automatically. The full name of this file
follows:
c:\Users\usr\WindowsApplication1\bin\Debug\ _
WindowsApplication1.exe
c:\Users\usr\WindowsApplication1\bin\Release\ _
WindowsApplication1.exe
The release version of the executable file is more efficient (in respect of the exe-
cution rate) in comparison with the debug version.
For loading the form, we must click twice on the program executable file in
Windows Explorer. Further, we can use the form for the calculation.
If we want to transfer the program with the form to another user, it is enough
to transfer the program executable file.
Let us return to programming in tabular processor Excel.
132
Chapter 2.
Programming in VBA
We review the main objects of the VBA programming language, which is the
Visual Basic extension in the sense that VBA includes the VB constructs. The
Excel table is considered as the user interface of macros.
Besides, we also consider creating Excel user-defined functions and working
with Excel Macro Recorder, Personal Macro Workbook and the reference sys-
tems.
133
Chapter 2. Programming in VBA
The user-defined forms, developed in Section 1.23, were loading from the
VB window, for example, by clicking on arrow ► of the standard toolbar. How-
ever, it is desirable to load the form from the Excel window.
Below, we will consider the form-loading program.
Let us open the BookForm workbook of Excel (p. 127), go to the VB window
and fulfill Insert > Module.
We enter the following simple program into the code window of the inserted
module:
Sub LoadingForm()
UserForm1.Show
End Sub
UserForm1.TextBoxB.SetFocus
Sub LoadingForm()
UserForm1.TextBoxB.SetFocus
UserForm1.Show
End Sub
134
2.1. Loading the form from the Excel window. Running the program executable file
Let us save the Excel workbook with the LoadingForm program under the
old name of BookForm.
The following program (in the code window) allows opening the Notepad
window in Excel:
Sub StartEXE()
Dim RetVal As Integer 'for function Shell
RetVal = Shell("c:\Windows\notepad.exe",1)
End Sub
In this program, we see the call of the Shell function, as in the Addition
program on p. 106.
To open the Notepad window, we must run the StartEXE program by ful-
filling Developer (or View) > Macros > line StartEXE > Run. Besides, we can
appoint a combination of keys for opening the Notepad window.
By using the StartEXE macro, we can run any executable file, in particular,
created in Visual Basic Environment, which is a part of Microsoft Visual Studio
(Section 1.24). For that, c:\Windows\notepad.exe must be replaced by
the full name (without spaces) of this executable file.
135
Chapter 2. Programming in VBA
The control elements of Section 1.23 can be placed on the Excel worksheet.
For example, to create the form-loading button, we must fulfill the following.
1. In the Excel window with open workbook BookForm, fulfill Developer >
Insert in area Controls. The window with control elements appears (Fig. 2.2).
Fig. 2.2. The Excel window with control elements below the Insert button
2. Click on the Button element in the Form Controls area of the last win-
dow, and then click on any cell of the Excel worksheet. The Assign Macro win-
dow opens (Fig. 2.3).
3. Click on the New button. The VB window opens (Fig. 2.4), and button
Button1 selected by 6 markers appears on the worksheet (Fig. 2.5).
4. Insert operator UserForm1.Show into the program blank in the code
window depicted in Fig. 2.4. The following program is the result:
Sub Button1_Click()
UserForm1.Show
End Sub
136
2.2. Layout of the control elements on the Excel worksheet
Fig. 2.3
Fig. 2.4. The VB window with Module1 and Module2 in the project window
137
Chapter 2. Programming in VBA
Now, for loading the form pictured in Fig. 1.31, all we have to do is click on
button Button1.
To change the inscription on the button:
1) select the button as follows:
right click on it;
then perform the Cancel command in the context menu opened;
2) edit the inscription as usual text;
3) click on area outside the button to remove its selection.
To remove the selected button, we must press the Delete key.
The Excel worksheet with the control elements plays the role of the form. For
beauty of this “form”, it is possible to remove gridlines from the Excel work-
sheet. For that, in the Excel window, we must fulfill View > turn off Gridlines in
area Show.
If we want to use the button for opening the Notepad window, program
Button1_Click must be changed as follows:
Sub Button1_Click()
Dim RetVal As Integer 'for function Shell
RetVal = Shell("c:\Windows\notepad.exe",1)
End Sub
138
2.3. User-defined functions of Excel
Our study of Visual Basic began with the Pythagoras program (p. 17)
intended for calculating the hypotenuse length. Let us consider the following
function for solving this simple task:
Function Hypotenuse(a, b)
Hypotenuse = Sqr(a ^ 2 + b ^ 2)
End Function
This function declaration should be entered into the code window after insert-
ing a module, for example Module1, into the active Excel workbook. As a result,
the Hypotenuse function appears in the User Defined category of the Excel
functions library. To verify this, we must fulfill the following two operations:
1) click on the fx button of the Excel formula bar;
2) in the Insert Function window opened (the first window of Function
Wizard), enter User Defined into box Or select a category by means of the drop-
down list.
We see line Hypotenuse in list Select a function (Fig. 2.6), i.e., the considered
function is available in category User Defined of the Excel functions library.
Let us interrupt the operation of Function Wizard by clicking on the Cancel
button in the Insert Function window.
The created function is used, for example, as follows:
1) into two cells on the Excel worksheet, enter the lengths of the triangle’s
legs, for example, 30.02 and 40 into A2 and B2, respectively;
2) select a cell for the hypotenuse length, for example, C2;
3) in the Excel formula box after =, put the Hypotenuse function whose
arguments are the addresses of the cells with the lengths of the triangle’s legs
(we must type a semicolon between the arguments instead of a comma accepted
in Visual Basic);
4) calculate in one of the following two ways:
by clicking on the tick button of the Excel formula bar;
by pressing the Enter key.
As a result, the hypotenuse length appears in the selected cell (Fig. 2.7).
139
Chapter 2. Programming in VBA
140
2.3. User-defined functions of Excel
Sub Pythagoras()
Dim a As Single
Dim b As Single
Dim c As Single
a = 3
b = 4
c = Hypotenuse(a, b)
End Sub
This text must be put into a new module, for example, by name Module2.
By executing the last program step-by-step, we can verify its operational
capability.
In Excel, when transposing a matrix (cell range) relative to the main diagonal
(Section 1.21), its rows and columns interchange their positions. For such trans-
position, Excel has the built-in TRANSPOSE function, which is available in
category Lookup & Reference of the functions library. It is an example of the
function returning an array of numbers, instead of one number (the SQRT func-
tion returns a number, see p. 17).
The TRANSPOSE function is used as follows:
1) enter a matrix (containing, for example, 3 rows and 4 columns) into Excel
cells;
2) select the cell range (containing 4 rows and 3 columns) for the transposi-
tion result;
3) into the Excel formula box after =, enter the TRANSPOSE function
whose argument is the source range (containing 3 rows and 4 columns);
4) calculate in one of the following two ways:
by clicking on the tick button of the Excel formula bar when keys Ctrl
and Shift are simultaneously pressed;
by pressing the Enter key when keys Ctrl and Shift are simultaneously
pressed (that is, by pressing Ctrl + Shift + Enter).
The transposition result appears in the selected cell range.
141
Chapter 2. Programming in VBA
Function Wizard simplifies the use of the TRANSPOSE function. For trans-
posing the matrix, we have to click on OK in the Function Arguments window
when keys Ctrl and Shift are simultaneously pressed.
It is interesting to create a user-defined function for transposing a matrix (cell
range) relative to its auxiliary diagonal according to formula (1.3) on p. 109.
This function’s declaration follows:
Listing 2.1
Function TRANSPOSEA(massive As Variant) As Variant
Dim m As Integer, n As Integer
Dim i As Integer, j As Integer
Dim R() As Variant 'resulting matrix
m = massive.Rows.Count 'quantity of rows
n = massive.Columns.Count 'quantity of columns
ReDim R(1 To n, 1 To m) 'specification of size
For j = 1 To n
For i = 1 To m
R(j, i) = massive(m + 1 - i, n + 1 - j)
Next i
Next j
TRANSPOSEA = R
End Function
=TRANSPOSEA(A1:D3)
142
2.3. User-defined functions of Excel
While using Function Wizard for the matrix transposition, we have to click
on OK in the Function Arguments window when keys Ctrl and Shift are simulta-
neously pressed.
It is interesting to compare the TRANSPOSEA function with the program of
Section 1.22. By the number of operators, the function is four times shorter than
the program. Besides, the function can be used when creating Excel macros by
means of Excel Macro Recorder (Section 2.5).
Note that the name of the formal parameter of the TRANSPOSEA function
can differ from massive, for example, name diapason may be used.
When operating with the matrices containing a large number of columns, it is
convenient to use the R1C1 reference style, in which the Excel columns are
numbered by natural numbers instead of letters.
For setting the R1C1 reference style, we must fulfill the following operations:
1) click on the File button in Excel;
2) Options > Formulas;
3) turn on option R1C1 reference style in area Working with formulas of the
Excel Options window;
4) click on the OK button.
143
Chapter 2. Programming in VBA
144
2.5. Excel Macro Recorder
145
Chapter 2. Programming in VBA
1) select all cells on the worksheet by clicking on the intersection of the top
line (with numbers of columns) and the left column (with numbers of rows);
2) activate the Home tab;
3) in area Number, set the Currency format by using the drop-down list.
7. Select the R14C5 cell by clicking on it.
8. Developer > Stop Recording (in area Code) or View > arrow Macros
(in area Macros) > Stop Recording.
Fig. 2.9. The Record Macro window before clicking on the OK button
146
2.5. Excel Macro Recorder
For starting the MR macro from the Excel window, one of the following two
ways is used:
simultaneous pressing keys Ctrl and m;
Developer (or View) > Macros > line MR > Run.
When executing the macro, the computer repeats actions enumerated in items
4 — 7.
After restoring the A1 reference style, let us save the Excel workbook with
the MR macro (which is the result of using Excel Macro Recorder) under the
name of BookMacrorecorder. During the save, we have to set the following file
type: Excel Macro-Enabled Workbook.
For removing the MR macro, we must fulfill the following operations:
Developer (or View) > Macros > line MR > Delete > Yes. However, we will not
delete the macro because it will be required in the next sections.
147
Chapter 2. Programming in VBA
There is the possibility of editing this code created by using Excel Macro
Recorder.
Let us assume that we want to set content of cell R14C5 (that is, E14) by
means of the standard window. For that, we type the following operator above
the last line of Listing 2.2:
ActiveCell.Formula = _
InputBox("Enter price in dollars" _
& vbCrLf & "into the active cell")
148
2.6. VBA code generated by Excel Macro Recorder and its editing
149
Chapter 2. Programming in VBA
We put a value, for example 12, into text box Enter price in dollars into the
active cell. After clicking on the OK button, the text box content appears in cell
R14C5 (Fig. 2.12). The dollar sign in front of 12.00 is because of the Currency
format of the cell.
150
2.7. Objects and events
All modern programming languages (in particular, Visual Basic and VBA)
are object- and event-oriented.
The object orientation is based on partitioning the subject area (for which we
are developing a program) and clustering the parts.
The program’s part, which corresponds to the cluster, is named object.
The object’s characteristics are named properties.
Actions performed over the object are named methods.
Examples of the subject area are problems of modeling financial risks, semi-
conductor devices and evolution of stars (p. 47), as well as Visual Basic and
VBA themselves.
Examples of the object are the Visual Basic objects, which were considered
in Section 1.23: UserForm, Label, TextBox, CommandButton and CheckBox.
The event orientation is based on the following concepts:
“event” — the object’s qualitative change, which follows from work of
the user or computer;
“handler for event” — the command set, executed by the computer when
the event occurs.
An example of the event is the click on the Account button in the user-
defined form, for example, depicted in Fig. 1.28. Because of handling this event,
the ComButCalc_Click program execution is started.
The VBA programming language is intended for creating programs in the
Microsoft Office applications, such as word processor Word, tabular processor
Excel, technical editor Visio, database management system Access, etc. VBA
differs from Visual Basic in the presence of specific objects of Microsoft Office
and of its applications.
We will be interested in the so-called Excel objects intended for Excel VBA
Programming. Examples of such objects are Workbook, Worksheet, Range and
ActiveCell.
Operators intended for work with an object make the following:
setting object properties;
returning object properties into the program;
applying object methods.
151
Chapter 2. Programming in VBA
object.property = expression
object.property
object.method
The operator of applying the Add method is the exception. It creates a new
object, subobject, and adds it to object. The syntax of this operator
follows:
In this syntax, Set is the keyword, variable is a variable of the same data
type as subobject.
Applying the Add method is similar to calling the MsgBox procedure of
Visual Basic, which is both a subroutine and function.
An object hierarchy exists. The highest in the hierarchy of the application is
the Application object, i.e., all other objects “are included” in it. The Application
object reminds the Russian nested doll, but (unlike the nested doll) several
objects may be included in each object.
The full object name is a sequence of the object names separated by a point,
at that, this sequence begins with Application. For example,
Application.Workbooks("Archive").Worksheets("Cod"). _
Range("A1")
152
2.7. Objects and events
in VBA for Excel is the full name of the Range("A1") object or the reference
to the A1 cell on the Cod worksheet of the Archive workbook.
The use of the full object name is not necessary. Often, we can use the
incomplete name, i.e., without names of the objects activated at present. For
example, if the Archive workbook is active, then the full name of the
Range("A1") object may be shortened as follows:
Worksheets("Cod").Range("A1")
As before, this is the reference to the A1 cell on the Cod worksheet of the
Archive workbook.
In the above VBA notations, strings are in the parentheses. These strings may
be compound.
An example of using compound strings is the following operator:
Because of its execution, the following cell is selected on the active Excel work-
sheet: the intersection of the G column and the row whose number is equal to the
number of days from the century beginning.
We advise the reader to do the following:
1) type the last operator above line End Sub of program Century_20
(p. 25);
2) execute the obtained program;
3) pay attention to the position of the Excel cell activated.
We see that the object construct is similar to the record (Section 1.18). There-
fore, as the first approximation, the object can be considered as the built-in
record whose creation operator (the Type operator) is hidden from the program
developer.
In addition to properties and methods, some objects of VBA are also charac-
terized by events. However, it does not relate to the main Excel objects, which
will be considered below.
153
Chapter 2. Programming in VBA
It was mentioned above that the Application object occupies the top level in
the object hierarchy of Excel. This means that the Application object controls the
settings of the application, i.e., such settings as are in window Excel Options
(to open this window, we must fulfill File > Options). Operator
Application.ReferenceStyle = xlR1C1
in the MR macro text, which was created by means of Excel Macro Recorder (see
Listing 2.2 on p. 148), speaks about this role of the Application object.
However, the Application object not only changes parameters of Excel. If we
want to use Excel functions when programming in VBA, the Application object
is also necessary for us.
Let us use built-in functions AVERAGE and SUM of Excel for processing
range A1:A4 on the Sheet1 worksheet.
1. Insert a module into the active Excel workbook. Enter program
Listing 2.3
Sub BuiltinFunctions()
Dim W As Single
1: W = Application. _
Average(Worksheets("Sheet1").Range("A1:A4"))
MsgBox "Average = " & CStr(W)
2: W = Application. _
Sum(Worksheets("Sheet1").Range("A1:A4"))
MsgBox "Sum = " & CStr(W)
End Sub
154
2.8. Object Application
The built-in Excel functions are properties of the Application object. When
executing operators 1 and 2, properties Average and Sum return with parameter
Worksheets("Sheet1").Range("A1:A4").
In addition to Excel functions, the Application object has other properties.
From the long list of the properties, we will consider the following.
ActiveWorkbook — the active workbook.
ActiveSheet — the active worksheet of the active workbook (in our opin-
ion, ActiveWorksheet would be a more suitable name of this property).
ActiveCell — the active cell on the active worksheet of the active work-
book.
As an example of returning the ActiveCell property, let us consider the fol-
lowing program, which sets the italic font for the active cell and puts text Report
for May into this cell.
155
Chapter 2. Programming in VBA
Sub ItalicFont()
With Application.ActiveCell
.Font.Italic = True
.Value = "Report for May"
End With
End Sub
Application.Calculation = xlCalculationAutomatic
Application.Dialogs(xlDialogOpen).Show
UserForm1.Show
156
2.8. Object Application
1. Above the last line of the BuiltinFunctions macro (p. 154), insert
the following operator of displaying the document saving window:
Application.Dialogs(xlDialogSaveAs).Show
Sub BuiltinFunctions()
Dim W As Single
1: W = Application. _
Average(Worksheets("Sheet1").Range("A1:A4"))
MsgBox "Average = " & CStr(W)
2: W = Application. _
Sum(Worksheets("Sheet1").Range("A1:A4"))
MsgBox "Sum = " & CStr(W)
Application.Dialogs(xlDialogSaveAs).Show
End Sub
Application.Dialogs(xlDialogSaveAs).Show
With Application.Dialogs(xlDialogSaveAs)
.Show
End With
157
Chapter 2. Programming in VBA
The With operator may include both properties and methods. As an exam-
ple, let us consider the following new version of the BuiltinFunctions
macro:
Sub BuiltinFunctions()
Dim W As Single
1: W = Application. _
Average(Worksheets("Sheet1").Range("A1:A4"))
MsgBox "Average = " & CStr(W)
2: W = Application. _
Sum(Worksheets("Sheet1").Range("A1:A4"))
MsgBox "Sum = " & CStr(W)
With Application
.ActiveCell.Value = "Report for May"
'property Value
.Dialogs(xlDialogSaveAs).Show 'method Show
End With
End Sub
During the execution, text Report for May appears in the active cell.
From the list of methods of the Application object, we will consider the fol-
lowing: Quit, Calculate, OnTime.
Quit — quit Excel.
The operator of applying the Quit method follows:
Application.Quit
Application.Calculate
Worksheets("Report7").Calculate
Worksheets("Report7").Range("A1:C10").Calculate
158
2.8. Object Application
the execution of the third operator leads to the calculation in the A1:C10
range on the Report7 worksheet of the active workbook.
As we know, the execution of operator
Application.Calculation = xlCalculationManual
In the MyMacro macro, operator 1 writes the current time into the A1 cell.
Operator 2 starts MyMacro one second after the current moment; therefore,
operator 1 is executed every second, i.e., the A1 cell content is updated every
second.
For the initial start of MyMacro, we must fulfill Developer (or View) >
Macros > line MyMacro > Run.
Let us depict the time starting from the moment of opening the Excel work-
book (containing the corresponding macro). For this purpose, we use name
Auto_Open instead of MyMacro. The new version of the last program follows:
Sub Auto_Open()
1: Range("A1") = Time
2: Application.OnTime Now + TimeValue("00:00:01"), _
"Auto_Open"
End Sub
159
Chapter 2. Programming in VBA
Sub MyMa1()
Range("G1") = 13.333
End Sub
Sub MyMa2()
Range("G2") = Time
Application.OnTime Now + TimeValue("00:00:01"), _
"MyMa2"
End Sub
These three macros should be put into one module or different modules of the
same Excel workbook.
160
2.9. Objects Workbook, Workbooks and ActiveWorkbook
Object Workbook follows right after object Application in the object hierar-
chy. It is easy to understand the following properties of the Workbook object.
Name — the workbook name with its extension.
The possible extensions of the name follow:
.xlsm if the workbook contains macros;
.xlsx if macros are absent in the workbook, etc.
The file name together with its extension frequently is also called the file name.
As a rule, it does not lead to any confusion.
Path — the path to the workbook in the file system of Windows.
FullName — the workbook name with its path and extension, i.e., the
workbook full name.
Let us consider the following three methods of the Workbook object:
Close — closing the workbook;
Save, SaveAs — saving the workbook.
The SaveAs method differs from the Save method in that SaveAs has a list of
optional parameters, which includes FileName, FileFormat and Password.
Examples of using the properties and methods of the Workbook object are
given below, when considering objects of the Workbook data type. Here, “data
type” has the same sense as in expression “variables (records) of the Session data
type” on p. 91.
Objects of the Workbook type (“data” is omitted for brevity) have the proper-
ties and methods of the Workbook object.
The Workbooks object is an object containing all open Excel workbooks.
This object is also named as the Workbooks collection.
In VBA,
Workbooks("Personnel_department")
161
Chapter 2. Programming in VBA
Workbooks("Personnel_department").Activate
The window, containing the number of open workbooks and the OK button,
is displayed when executing the NumberofBooks macro. To terminate the
execution, we must click on OK.
It was mentioned in the previous section that ActiveWorkbook is a property
of the Application object, corresponding to the active workbook. As the Work-
book type object, the ActiveWorkbook property has the properties and methods
of the Workbook object.
To obtain examples of returning properties Name and FullName of the
Workbook object and of applying the Save method, let us fulfill the following:
1) in the Excel window with the BookMacrorecorder workbook (p. 147),
click on the Enable Content button of the Security Warning panel to allow the
MR macro to work;
2) Developer (or View) > Macros > line MR > Edit;
3) put operator block
1: Dim S As String
2: S = ActiveWorkbook.Name
3: MsgBox S
4: MsgBox ActiveWorkbook.FullName
5: ActiveWorkbook.Save
162
2.9. Objects Workbook, Workbooks and ActiveWorkbook
Because of executing operator 2, the S string has a value that is equal to the
name of the active workbook. Operator 3 displays this string (Fig. 2.16).
Let us click on the OK button (in the window depicted in Fig. 2.16) to con-
tinue executing the MR macro. Operator 4 displays the active workbook’s full
name (Fig. 2.17). After clicking on the OK button, operator 5 saves the active
workbook.
To obtain an example of returning the Path property of the Workbook object,
we will execute the MR macro with the following form of the operator intended
for displaying the full name:
163
Chapter 2. Programming in VBA
The window, depicted in Fig. 2.17, appears during the execution, as in the case
of the previous version of operator 4.
Fig. 2.17. The window with the full name of the active workbook
164
2.9. Objects Workbook, Workbooks and ActiveWorkbook
c:\Users\usr
c:\Users\usr\Hour0.xlsx.
165
Chapter 2. Programming in VBA
Operator 5 closes the Hour0 workbook, and operator 6 displays the message
about it (Fig. 2.19). Operator 7 performs exit from Excel.
In operator 1, we may replace the Workbook type by the Object data type
(Appendix 1) similar to the Variant data type familiar to us.
166
2.10. Objects Worksheet, Worksheets and ActiveSheet
The Worksheet object follows Workbook in the object hierarchy. Let us con-
sider the following properties of object Worksheet:
Name — the worksheet name;
Cells — one of the following:
the collection of all cells on the worksheet;
the single cell if we specify (by two integers in parentheses, through a
comma) the numbers of row and column whose intersection defines this cell.
The Cells property will be also considered in the next section, as applied to
the Range object.
We will consider the following two methods of the Worksheet object:
Activate — activating the worksheet;
Delete — deleting the worksheet.
Examples of using the properties and methods of the Worksheet object are
given below, when considering objects of the Worksheet type. The last objects
have the properties and methods of the Worksheet object.
The Worksheets object is an object containing all worksheets of the Excel
workbook. This object is also named as the Worksheets collection.
Its number or name can identify each worksheet of the Worksheets object.
For example, Worksheets(1) designates the 1st worksheet of the workbook, and
Worksheets(“Sheet1”) is the worksheet by name Sheet1. Worksheets(1) and
Worksheets(“Sheet1”) are objects of the Worksheet type.
As examples of applying the Activate and Delete methods of the Worksheet
object, let us consider the following operators:
Worksheets(3).Activate
Worksheets("Sheet2").Delete
The first operator activates the 3rd worksheet of the active workbook, and the
second operator deletes worksheet by name Sheet2 of the active workbook.
When working with object Worksheets, the application of the Add method
adds to the collection a new worksheet that becomes active at once. This applica-
tion is accompanied by return (into the program) of the created worksheet, which
167
Chapter 2. Programming in VBA
The window, containing the number of worksheets in the active Excel work-
book and the OK button, is displayed when executing the NumberofSheets
macro (Fig. 2.20). For terminating the execution, we have to click on OK.
Fig. 2.20
168
2.10. Objects Worksheet, Worksheets and ActiveSheet
An example of setting the Name property of the Worksheet object is the fol-
lowing operator:
ActiveSheet.Name = "July"
This program:
1) examines the values in cells A1:E4 on the active worksheet;
2) sets the green italic font when the value is negative.
Note that the object name can be excluded from VBA notation
ActiveSheet.Cells(i, j)
With Cells(i, j)
169
Chapter 2. Programming in VBA
1) put text
Listing 2.10
Sub NewSheet()
1: Dim wsNewWorksheet As Worksheet
2: Set wsNewWorksheet = Worksheets.Add
3: wsNewWorksheet.Name = Format(Date, "d mmmm yyyy")
End Sub
Sub NewSheet1()
1: Dim wsNewWorksheet As Worksheet
2: Set wsNewWorksheet = Worksheets(1)
3: wsNewWorksheet.Name = Format(Date, "d mmmm yyyy")
End Sub
As the execution result, the current date becomes the 1st worksheet’s name.
170
2.11. Objects Range, Selection and ActiveCell
Object Range follows the Worksheet object in the object hierarchy. It allows
working with the following elements of Excel:
range of cells;
range of columns;
range of rows;
single cell.
Let us consider some properties of the Range object.
Formula — the Excel formula with operands (cell addresses) in the A1
reference style.
For example, operators
Range("C2:F8").Formula = "=$A$4+COS($A$10)"
Range("D:E").Formula = "=$A$4+COS($A$10)"
Range("2:2").Formula = "=$A$4+COS($A$10)"
Range("B3").Formula = "=$A$4+COS($A$10)"
set the Formula property. These operators are respectively used to put formula
=$A$4+COS($A$10)
Worksheets("Sheet1").Range("G1:H4").FormulaR1C1 = _
"=SQRT(R5C8)^3+7.3"
sets the FormulaR1C1 property. This operator is used for entering formula
171
Chapter 2. Programming in VBA
=SQRT($H$5)^3+7.3
into the G1:H4 range on the Sheet1 worksheet (the R1C1 reference style option
may be turned on or off, see p. 143).
Address — the cell address.
Offset — the range shifted relative to the selected (active) range accord-
ing to two integers in parentheses.
In the Offset property, the first parameter (in parentheses) is the vertical shift,
and the second parameter is the horizontal shift. A comma is placed between
these parameters.
Value — one of the following:
the array of the range values;
the cell value, if the Range object corresponds to the single cell.
Columns — the collection of the range columns.
Rows — the collection of the range rows.
Cells — the collection of the range cells.
Note that we considered the Cells property regarding the Worksheet object in
the previous section.
Below, we will list some methods of the Range object.
Clear — the removal of the range contents.
For example, the following application of the Clear method clears cells
A1:F7 on the Sheet1 worksheet:
Worksheets("Sheet1").Range("A1:F7").Clear
172
2.11. Objects Range, Selection and ActiveCell
The Selection object allows working with the active (selected) cells. As the
Range type object, the Selection object has properties Columns, Rows and Cells.
Thus, properties
Selection.Columns
Selection.Rows
Selection.Cells
are the collections of columns, rows and cells of the selected range, respectively.
The following example program inserts the multiplication table into the
selected range on the active worksheet:
Listing 2.12
Sub MultiplicationTable()
Dim m As Integer, n As Integer
Dim i As Integer, j As Integer
1: m = Selection.Rows.Count 'quantity of rows
2: n = Selection.Columns.Count 'quantity of columns
3: For i = 1 To m
4: For j = 1 To n
5: Selection.Cells(i, j).Value = i * j
6: Next j
7: Next i
End Sub
Operators 1 and 2 contain the Count property whose return allows defining
the quantity of objects in the Selection.Rows and Selection.Columns
collections. Because of executing these operators, the quantities of rows and
columns in the selected range are assigned to the m and n variables, respectively.
Operator 5 may have the following form:
Selection.Cells(i, j) = i * j
173
Chapter 2. Programming in VBA
wbOldSelection.Select
=SUM(B1:B3)
into cell B4 on Sheet1, and click on the tick button of the Excel formula bar.
3. Go to Visual Basic Environment and insert a module into the active
workbook.
4. Enter the following text into the code window:
Listing 2.13
Sub PropofRange()
1: Worksheets("Sheet1").Range("A1").Select
2: ActiveCell.Offset(2, 3).Select
3: MsgBox "Current cell — " & ActiveCell.Address
4: MsgBox "Value in cell B4 = " & _
Range("B4").Value
5: MsgBox "Formula in cell B4: " & _
Range("B4").Formula
End Sub
174
2.11. Objects Range, Selection and ActiveCell
175
Chapter 2. Programming in VBA
176
2.12. Study of objects
177
Chapter 2. Programming in VBA
For obtaining information on the Select method of the Range object, we high-
light line Select in list Members of 'Range' and press the F1 key. As a result,
the Excel Help window, containing the necessary information, is displayed
(Fig. 2.23).
178
2.12. Study of objects
179
Chapter 2. Programming in VBA
We considered the main Excel objects. Now we can use the Excel table as the
user interface of programs.
Initially, we will create a macro for calculating the length of the leg of
a right-angled triangle with given lengths of the hypotenuse and the other leg.
In this macro, we will realize formula
b c2 a2
following from formula (1.1) on p. 16.
Let length a of the leg be in the A4 cell, length c of the hypotenuse be in C4.
Let B5 be intended for resulting length b. The macro has the following text:
Listing 2.14
Sub Leg()
Dim a As Single, b As Single, c As Single
a = Range("A4").Value
c = Range("C4").Value
If c < a Then
Range("B5").Value = "Error"
End 'immediate termination of macro
End If
b = Sqr(c ^ 2 - a ^ 2) 'according to Pythagoras
Range("B5").Value = b
End Sub
180
2.13. Using the Excel table as the user interface of programs
expression c < a accepts True when executing the Leg macro. In this case,
message Error appears in cell B5 and the End operator terminates the macro
execution. We encounter the End operator for the first time.
It is easy to understand the work of the following macro intended for trans-
posing a numerical matrix relative to its auxiliary diagonal according to formula
(1.3) on p. 109:
Listing 2.15
Sub TRANSPA()
Dim m As Integer, n As Integer
Dim i As Integer, j As Integer
m = Selection.Rows.Count 'quantity of rows
n = Selection.Columns.Count 'quantity of columns
For j = 1 To n
For i = 1 To m
Selection.Cells(j + m + 1, i) = _
Selection.Cells(m + 1 - i, n + 1 - j)
Next i
Next j
End Sub
Fig. 2.24. The Excel worksheet with the initial matrix and
the result of its transposing relative to the auxiliary diagonal
181
Chapter 2. Programming in VBA
182
2.14. Two more Excel macros. Personal Macro Workbook
183
Chapter 2. Programming in VBA
Fig. 2.26. The Record Macro window before clicking on the OK button
4. Developer > Stop Recording (in area Code) or View > arrow Macros
(in area Macros) > Stop Recording.
5. Open the VB window.
6. Click on line VBAProject (PERSONAL.XLSB) in the project explorer
window, and fulfill File > Save PERSONAL.XLSB.
7. Close the Excel window by clicking on the little cross in the top right
corner. If the window with a question about saving changes in Personal Macro
Workbook is displayed (when closing the Excel window), click on the Yes
button.
184
2.14. Two more Excel macros. Personal Macro Workbook
185
Chapter 2. Programming in VBA
c:\Users\usr\AppData\Roaming\Microsoft\Excel\XLSTART
where usr is the user name. File PERSONAL.XLSB is located in this folder.
If we want to transfer our Personal Macro Workbook to the user whose name
is usr2, we must copy the PERSONAL.XLSB file into folder
c:\Users\usr2\AppData\Roaming\Microsoft\Excel\XLSTART
of his computer.
Note that folder AppData (from “Application Data”) may be hidden in
Windows Explorer. To make a folder or file visible, we must fulfill the following
operations:
1) open the folder containing the hidden folder or file of interest;
2) Organize > Folder and search options;
186
2.14. Two more Excel macros. Personal Macro Workbook
187
Chapter 2. Programming in VBA
188
2.15. One more user-defined function of Excel
Fig. 2.28. The VB window with text of the Func9 function in the code window
In line 4, the quantity of rows in the massive range is the result of return-
ing property massive.Rows.Count. In line 5, the quantity of columns is the
result of returning property massive.Columns.Count.
In line 6, massive(i, j) is the reference to the corresponding cell of the
massive range.
The Func9 function is used as follows.
1. Enter values of matrix A, for example, into range D5:E8 on worksheet
Sheet4.
2. Assign a name, for example Test9, to the D5:E8 range. For this purpose:
1) select this range, and fulfill Formulas > Define Name in area Defined
Names;
2) in the open New Name window, type Test9 in text box Name;
3) enter Sheet4 into box Scope by means of the drop-down list (Fig. 2.29);
4) click on the OK button.
3. Enter formula
=PERSONAL.XLSB!Func9(Test9;2)
189
Chapter 2. Programming in VBA
In the above formula, an exclamation mark means that the Func9 function is
a part of file PERSONAL.XLSB.
4. Click on the tick button of the Excel formula bar.
Fig. 2.29. The New Name window with automatically filled box Refers to
The resulting number of values in the D5:E8 cells exceeding 2 appears in the
E11 cell (Fig. 2.30).
Below is the second way of using the Func9 function, without assigning
a name to the range with the A array.
Let us use Function Wizard as follows:
1) select a cell for the result, for example, Sheet4!E11;
2) click on the fx button of the Excel formula bar to start Function Wizard;
3) in the User Defined category of the open Insert Function window, high-
light the line corresponding to the Func9 function (Fig. 2.31), and click on the
OK button;
4) in the open Function Arguments window (Fig. 2.32), enter:
the source range (for example, D5:E8 on the Sheet4 worksheet) into the
first text box;
the h value, for example 2, into the second text box;
5) click on the OK button.
We see the former result: five values exceed h = 2 (Fig. 2.30).
Note that cell E11 and range D5:E8 may be on one or different worksheets of
the same Excel workbook.
190
2.15. One more user-defined function of Excel
Fig. 2.30. The source data and calculation result in the Excel window
191
Chapter 2. Programming in VBA
We advise the reader to calculate the values of function f (x) from Appen-
192
2.16. Digression. Change of Excel options
In the next four chapters of the book, languages VB and VBA will be used
for programming numerical methods. Besides, we will consider the Excel proce-
dures, which are a part of the add-ins, for solving some of our tasks.
For installing the necessary Excel add-ins, let us fulfill the following opera-
tions:
1) File > Options > Add-Ins;
2) enter Excel Add-ins into the Manage box by means of the drop-down list,
and click on the Go button;
3) in the open Add-Ins window, turn on options Analysis ToolPak and Solver
Add-in, and click on the OK button.
As a result, the Data Analysis and Solver commands appears in Excel Rib-
bon — on the Data tab, in the Analysis area.
We will need to tune Excel so that formulas are displayed in cells, instead of
results of calculations according to these formulas. For this purpose, we must
fulfill the following operations:
1) File > Options > Advanced;
2) turn on option Show formulas in cells instead of their calculated results
located below box Display options for this worksheet;
3) click on the OK button.
In this way, we change the contents of the cells with formulas on the work-
sheet specified in box Display options for this worksheet. The contents of the
cells without formulas do not change.
Upon turning off option Show formulas in cells instead of their calculated
results, the worksheet returns to the customary form, with values in the cells.
We will also need a workbook with the module for programs, realizing
numerical methods. To obtain it, let us fulfill the following:
1) open a blank workbook, and insert the Module1 module into it;
2) put text
Sub main()
End Sub
193
Chapter 2. Programming in VBA
194
Chapter 3.
Finite Difference Method
for Solving Differential Equations
195
Chapter 3. Finite Difference Method for Solving Differential Equations
Let u k , u[k ] , u k 1
, u[k 1]
, uk 2
, ..., ui 1
, u[i 1]
, ui , u[i ] , ui 1
, ...,
ur 2
, u[r 2]
, ur 1
, u[r 1]
, u r be the u (x) function values at the corre-
sponding nodes of the main and auxiliary grids.
A function, set on a grid, is called a grid function or a function in tabular
form (tabular function). An example of such function is u (x) considered above.
196
3.1. Finite difference analogs of derivatives for a uniform grid
We will come across grids and grid functions more than once.
Let us assume that function u (x) is continuous in segment [a, b] , has con-
tinuous derivatives of m 1 orders, and the m-th derivative exists, in other
words, function u (x) is differentiable m times. At that, in a neighborhood of any
interior point x of [a, b] , we can use Taylor’s formula [3] in the following form:
du 2 d 2u 3 d 3u
u( x ) u ( x) ( x) ( x) ( x) ...
1! dx 2! dx2 3! dx3
m 1 dm 1u
m
( x ) O( ). (3.1)
(m 1)! dxm 1
m
The O notation, O( ) , has the following sense (for natural m).
m
If ε is a small quantity, as in (3.1), O( ) means the quantity whose absolute
m
value is less or equal to C | | , where C is a positive constant, i.e., C is inde-
m
pendent of ε. In this case, O( ) is called the quantity of m-th order of small-
m
ness or the quantity of -th order.
If Ε is a large positive quantity, O( Ε m ) means the positive quantity whose
h ( h / 2) 2 d 2 u h ( h / 2) 2 d 2 u
u xi u ( xi ) ( xi ) u xi u ( xi ) ( xi )
2 2 dx 2 2 2 dx 2
h h
2 2
u[ i ] u[ i 1]
O(h 2 ) O(h 2 ) . (3.2)
h
Similarly, we can obtain two more expressions for the first derivative of the
u (x) function:
197
Chapter 3. Finite Difference Method for Solving Differential Equations
du ui 1
ui
(x ) O( h 2 ) , (3.3)
dx [ i ] h
du ui 1 ui 1
( xi ) O( h 2 ) . (3.4)
dx 2h
Using formulas (3.2) and (3.3), we can also obtain an expression for the
second derivative of u (x) as follows:
d 2u u ( x[ i ] ) u ( x[ i 1]
)
( xi ) O(h 2 )
dx2 h
ui 1
ui ui ui 1
h h ui 1
2u i ui 1
O(h 2 ) O(h 2 ) . (3.5)
h h 2
198
3.2. Finite difference scheme for the linear differential equation. The decomposition method
d 2u du
g ( x)
e( x)u f ( x) , (3.6)
dx2 dx
where g (x) , e(x ) and f (x) are given functions, u (x ) is an unknown function.
For uniqueness of the solution of this equation, we use the following left and
right boundary conditions:
A0 u ( a ) A1 u ( a ) A , (3.7)
B0 u (b) B1 u (b) B, (3.8)
where A and B are given parameters, A0 B0 1 , A1 B1 0 to begin with.
Let us consider a method for solving this boundary value problem, based on
replacing the derivatives by their finite difference analogs,
du ui 1
ui 1 d 2u ui 1
2u i ui 1
( xi ) , .( xi )
dx dx 2h h 2 2
These expressions follow from (3.4) and (3.5) if we neglect the summands of
second order of smallness, O( h 2 ) .
Let xi be an internal node of the main grid (Fig. 3.1), i.e., node xi does not
coincide with points a and b. Equation (3.6) at this node looks like
d 2u du
( xi ) g ( xi ) ( xi ) e( xi ) u ( xi ) f ( xi ) .
dx2 dx
Multiplying both sides of this equality by h 2 and substituting the finite differ-
ence analogs of the derivatives, we get the following linear algebraic equation:
u
i i 1
u
i i
u
i i 1 i
, (3.9)
where ui 1
, ui , u i 1
are unknown variables, i = k + 1, k + 2, ..., r – 2, r – 1,
199
Chapter 3. Finite Difference Method for Solving Differential Equations
i
1 0.5 g i h ,
i
ei h 2 2,
i
1 0.5 g i h , (3.10)
i
fi h 2 .
In the last four expressions, g i , ei and fi are the values of the coefficients
and right-hand side of equation (3.6) at node xi : g i g ( xi ) , ei e ( xi ) ,
fi f ( xi ) , i = k + 1, k + 2, ..., r – 2, r – 1.
Boundary conditions (3.7) and (3.8) can be written as follows:
u
k k
u
k k 1 k
, (3.11)
u
r r 1
u
r r r
, (3.12)
where k r
2, k r
0, k
2A , r
2B .
The system of linear algebraic equations (3.9), (3.11) and (3.12) is called the
finite difference scheme for boundary value problem (3.6) — (3.8). More pre-
cisely, this system is called the one-dimensional finite difference scheme because
it corresponds to the problem with one spatial coordinate.
Using the definitions of matrix multiplication and equality (Section 1.21), we
can write scheme (3.9), (3.11), (3.12) as the following matrix equation:
k k
0 0 ... 0 0 0 0
k 1 k 1 k 1
0 ... 0 0 0 0
0 k 2 k 2 k 2
... 0 0 0 0
. . . . . . . . .
0 0 0 0 ... r 2 r 2 r 2
0
0 0 0 0 ... 0 r 1 r 1 r 1
0 0 0 0 ... 0 0 r r
uk k
uk 1 k 1
uk 2 k 2
... ... .
ur 2 r 2
ur 1 r 1
ur r
200
3.2. Finite difference scheme for the linear differential equation. The decomposition method
The coefficient (system) matrix, which is a part of this matrix equation, has
the so-called tridiagonal form: nonzero elements are only on the main diagonal,
the first “diagonal” below this and the first “diagonal” above the main diagonal.
Finite difference scheme (3.9), (3.11), (3.12) is usually solved by the decom-
position method [4] whose main advantage is its efficiency in comparison with
other methods for solving this system of linear algebraic equations:
for calculating the values of the n r k 1 unknowns ( u k , u k 1 ,
uk 2
, ..., u r 2
, ur 1
, u r ) by the decomposition method, O(n) arithmetic
operations must be performed (p. 203);
the solution of the system of equations (3.9), (3.11) and (3.12) by the
Gaussian elimination method (Sections 3.9 and 3.10) requires O ( n3 ) arithmetic
operations (p. 227).
The decomposition method includes two stages, which are called the forward
and backward sweeps. To obtain formulas for the sweeps, let us connect the
unknowns, u i 1 and ui , through formula
ui 1
Pi ui Qi , (3.13)
where Pi , Q i are the auxiliary unknowns, i = r, r – 1, ..., k + 1.
After substituting the last expression into equation (3.9), we obtain
i i
Q
i i
ui ui 1
P
i i i
P
i i i
or
ui Pi u
1 i 1
Qi 1
,
where Pi 1
and Qi 1
are determined by the following recurrence formulas:
i
Pi 1
, (3.14)
P
i i i
i i
Qi
Qi 1
. (3.15)
i i
P i
201
Chapter 3. Finite Difference Method for Solving Differential Equations
k
Pk 1
, (3.16)
k
k
Qk 1
, (3.17)
k
D2 r r
Qr
ur . (3.18)
D r r
P r
202
3.2. Finite difference scheme for the linear differential equation. The decomposition method
The use of the forward and backward sweeps gives the values of unknown
u k , u k 1 , u k 2 , ..., u r 2 , u r 1 , u r , i.e., the solution of finite difference
scheme (3.9), (3.11), (3.12) for linear differential equation (3.6) with boundary
conditions (3.7) and (3.8). The calculated values of u k , u k 1 , u k 2 , ..., u r 2 ,
ur 1
, u r approximate the exact solution of problem (3.6) — (3.8) at the nodes
of the main grid on segment [a, b] .
A simple analysis of formulas (3.14) and (3.15) of the forward sweep shows
that it requires O(n) arithmetic operations, n . A similar analysis of formu-
la (3.13) shows that the backward sweep also requires O(n) arithmetic opera-
tions. Thus, the solution of finite difference scheme (3.9), (3.11), (3.12) by the
decomposition method requires O(n) arithmetic operations.
203
Chapter 3. Finite Difference Method for Solving Differential Equations
i
1 (3.20)
P
i i i
for all values of i from k + 1 to r – 1. If this condition is satisfied, then:
1) small error i (which is a part of the calculated value of Q i ) goes into
the value of Qi 1
without increase;
i
i 1 i
P
i i i
204
3.3. Sufficient stability conditions for the decomposition method
i 2 i 2
Pi 1
1 i
O( i
) Pi 1
Pi 1 i
O( i
).
P
i i i
P
i i i
That is, the algorithm of the calculation according to formula (3.14) is stable.
205
Chapter 3. Finite Difference Method for Solving Differential Equations
Thus, the simultaneous satisfaction of inequalities (3.19) and (3.20) for all
values of i is enough for stability of the forward and backward sweeps, i.e., of
the decomposition method in general.
By means of conditions (3.19) and (3.20), we will obtain other stability con-
ditions of the decomposition method, which are more convenient to use.
Let us assume that
0 Pk 1
1 (3.22)
and inequalities
i i
, i i i
, (3.23)
i
0 (3.24)
are simultaneously satisfied for all values of i. Then inequalities (3.19) and
(3.20) are satisfied for all values of i, i.e., the decomposition method is stable.
To prove the last assertion, we transform formula (3.14) as follows:
i i i
Pi 1
,
P
i i i i
( i i i
) i
(1 Pi ) i i
where i
( i i i
) i
(1 Pi ) .
Similarly, we obtain the following expression for a part of formula (3.15):
i i
.
P
i i i i i
i
0 1. (3.26)
P
i i i
According to (3.22), inequalities (3.25) and (3.26) are satisfied for i = k + 1,
k + 2, ..., r – 1. As the consequence of this, inequalities (3.19) and (3.20) are satis-
fied for all values of i, i.e., the decomposition method is stable.
We proved that conditions (3.22) — (3.24), as well as conditions (3.19) and
(3.20), are the sufficient stability conditions for the decomposition method.
Because coefficients i , i and i are defined by expressions (3.10), the
consequence of the obtained stability conditions is the unconditional stability of
the decomposition method for solving boundary value problem (3.6) — (3.8), for
which the following conditions are satisfied:
206
3.3. Sufficient stability conditions for the decomposition method
1) g (x) 0 for all values of x from a to b, i.e., equation (3.6) looks like
d 2u
e ( x )u f ( x) ;
dx 2
2) e(x) 0 for all values of x;
3) left boundary condition (3.7) is such that 0 Pk 1
1.
The unconditional stability means the stability for arbitrary step h of the grid.
207
Chapter 3. Finite Difference Method for Solving Differential Equations
Thanks to the unconditional stability of solving the last boundary value prob-
lem (formulated at the end of the previous section), the substitution into equation
(3.6), which excludes the first derivative of u (x ) , is of interest. We will show
that such substitution looks like
x
u ( x) U ( x ) exp 0.5 g ( y ) dy . (3.27)
a
d 2u d 2U dU x
g (0.25g 2 0.5 g ) U exp 0.5 g ( y )dy . (3.29)
dx 2 dx 2 dx a
d 2U
E ( x )U F ( x) , (3.30)
dx 2
where
E e( x) 0.25g 2 ( x) 0.5g ( x) , (3.31)
x
F f ( x ) exp 0.5 g ( y ) dy . (3.32)
a
208
3.4. Simplification of the second-order linear differential equation
A2 U ( a ) A1U ( a ) A3 , (3.33)
where
A2 A0 0.5 A1 g ( a ) , (3.34)
A3 A. (3.35)
After substituting expressions (3.27) and (3.28), in which x b , into condi-
tion (3.8), we have the following right boundary condition:
B2 U (b ) B1U (b ) B3 , (3.36)
where
B2 B0 0.5 B1 g (b) , (3.37)
b
B3 B exp 0.5 g ( y ) dy . (3.38)
a
We will use substitution (3.27) not only in this chapter, but in the next chap-
ter too.
209
Chapter 3. Finite Difference Method for Solving Differential Equations
For solving equation (3.6) with boundary conditions (3.7) and (3.8) by the
decomposition method, we insert module Module2 into the BookNM workbook
(p. 194) and put the following subroutine declaration into this module:
Listing 3.1
Sub fb(ByVal k, ByVal r, ByVal h, ByVal A, ByVal B, _
ByRef G() As Double, ByRef E() As Double, _
ByRef F() As Double, ByRef U() As Double)
Const BETAK = -2, GAMMAK = 0
Dim DELTAK As Double
Const ALPHAR = 0, BETAR = -2
Dim DELTAR As Double
Dim alpha As Double, beta As Double
Dim gamma As Double, delta As Double
Dim i As Integer, w As Double
Dim P() As Double: ReDim P(k + 1 To r)
Dim Q() As Double: ReDim Q(k + 1 To r)
DELTAK = -2 * A
DELTAR = -2 * B
'Forward sweep:
P(k + 1) = -GAMMAK / BETAK
Q(k + 1) = DELTAK / BETAK
For i = k + 1 To r - 1
w = 0.5 * G(i) * h
alpha = 1 - w
beta = E(i) * h ^ 2 - 2
gamma = 1 + w
delta = F(i) * h ^ 2
w = alpha * P(i) + beta
P(i + 1) = -gamma / w
Q(i + 1) = (delta - alpha * Q(i)) / w
Next i
'Backward sweep:
210
3.5. Program realization of the decomposition method
211
Chapter 3. Finite Difference Method for Solving Differential Equations
The first three rows of this table contain the values of parameters c and b and
the number of steps, l = r – k. The bottom row contains titles of the Excel
columns intended for the solution result, i.e., for the u (x) function in tabular
form.
212
3.6. Examples of using the decomposition method
Instead of text
Sub main()
End Sub
we enter the following program text into Module1 of the BookNM workbook:
Listing 3.2
Sub main()
Dim X() As Double
Dim G() As Double
Dim E() As Double
Dim F() As Double
Dim U() As Double
Dim c As Double, b As Double, l As Integer
Dim h As Double, i As Integer
c = Selection.Cells(1, 2)
b = Selection.Cells(2, 2)
l = Selection.Cells(3, 2)
h = b / l
ReDim X(5 To 5 + l)
ReDim G(5 To 5 + l)
ReDim E(5 To 5 + l)
ReDim F(5 To 5 + l)
ReDim U(5 To 5 + l)
For i = 5 To 5 + l
X(i) = (i - 5) * h
1: G(i) = X(i) ^ 2
2: E(i) = -3 * c * X(i)
3: F(i) = 0
Next i
4: Call fb(5, 5 + l, h, 1, 0, G, E, F, U)
For i = 5 To 5 + l
Selection.Cells(i, 1) = X(i)
5: Selection.Cells(i, 2) = U(i)
Next i
End Sub
It was mentioned above that the source data for this program are the values
located in the Excel table (Fig. 3.2a). We must select this table before the pro-
gram execution (Fig. 3.2b).
213
Chapter 3. Finite Difference Method for Solving Differential Equations
The calculated coordinates of the grid nodes and values of the solution are
located in columns x and u (Fig. 3.3). For obtaining the u (x) graph, located on
the Excel worksheet, we must fulfill the following operations:
1) select the values of x and u, i.e., the B6:C21 range;
2) activate the Insert tab;
3) perform the Insert Scatter command in area Charts;
4) perform command Scatter with Smooth Lines.
214
3.6. Examples of using the decomposition method
By substitution (3.27),
x
x3
u U ( x ) exp 0.5 y 2 dy U ( x ) exp , (3.41)
0
6
we can bring boundary value problem (3.39), (3.40) to form (3.30), (3.33),
(3.36), i.e.,
d 2U
[0.25x 4 (3c 1) x ] U 0, (3.42)
2
dx
U (0) U (b) 0 .
1, (3.43)
As we see, derivative dU / dx is absent in equation (3.42), i.e., the 1st item
of the conditions on p. 207 is satisfied. The 2nd and 3rd items are also satisfied
because:
the coefficient in front of U is less or equal to zero when x ≥ 0;
Pk 1 0 according to (3.16) and (3.11).
Thus, the decomposition method is unconditionally stable for solving boundary
value problem (3.42), (3.43).
The following program is used as the previous one.
215
Chapter 3. Finite Difference Method for Solving Differential Equations
Listing 3.3
Sub main()
Dim X() As Double
Dim G() As Double
Dim E() As Double
Dim F() As Double
Dim U() As Double
Dim c As Double, b As Double, l As Integer
Dim h As Double, i As Integer
c = Selection.Cells(1, 2)
b = Selection.Cells(2, 2)
l = Selection.Cells(3, 2)
h = b / l
ReDim X(5 To 5 + l)
ReDim G(5 To 5 + l)
ReDim E(5 To 5 + l)
ReDim F(5 To 5 + l)
ReDim U(5 To 5 + l)
For i = 5 To 5 + l
X(i) = (i - 5) * h
1: G(i) = 0
2: E(i) = -0.25 * X(i) ^ 4 - (3 * c + 1) * X(i)
3: F(i) = 0
Next i
4: Call fb(5, 5 + l, h, 1, 0, G, E, F, U)
For i = 5 To 5 + l
Selection.Cells(i, 1) = X(i)
5: Selection.Cells(i, 2) = U(i) * _
Exp(-X(i) ^ 3 / 6)
Next i
End Sub
This program solves boundary value problem (3.42), (3.43) and then calcu-
lates the u (x) dependence by means of formula (3.41). It differs from program
Listing 3.2 in operators 1, 2 and 5. The result of using program Listing 3.3, the
u (x) function in tabular form, is close to the previous result depicted in Fig. 3.3.
Boundary value problem (3.42), (3.43) will be also used in Section 4.11 to
demonstrate the cubic spline method for solving the second-order linear differen-
tial equation.
216
3.7. Examples of the computing error. Instability and loss of accuracy
217
Chapter 3. Finite Difference Method for Solving Differential Equations
ReDim F(5 To 5 + l)
ReDim U(5 To 5 + l)
For i = 5 To 5 + l
X(i) = (i - 5) * h
1: G(i) = c
2: E(i) = 0
3: F(i) = c
Next i
4: Call fb(5, 5 + l, h, 0, b, G, E, F, U)
For i = 5 To 5 + l
Selection.Cells(i, 1) = X(i)
5: Selection.Cells(i, 2) = U(i)
Next i
End Sub
This program is used as the programs of the previous section. In Fig. 3.4, we
see the execution results for three values of c, equal to 10, 1017 and 1018.
For problem (3.44), (3.45), it is easy to make sure that conditions (3.22) and
(3.23) are satisfied for any positive values of c and h.
For h = b / l = 0.1, we can state the following about
i
1 0.5 g i h 1 0.5ch 1 0.05c ,
condition (3.24) and the stability with respect to the computing error:
for c = 10, the value of i is positive, i.e., condition (3.24) is satisfied,
therefore, the decomposition method is stable;
for c = 1017 and 1018, the value of i is negative, i.e., condition (3.24)
is not satisfied, therefore, the decomposition method can be either stable or
unstable.
The sign change of i occurs at c = 20.
According to Fig. 3.4a and 3.4b, an appreciable deviation of the calculated
u (x) dependence from the exact u (x) dependence, u ( x) x , appears at value
c = 1017, which exceeds value c = 20 by several orders of magnitude. It follows
from the fact that sufficient stability conditions (3.22) — (3.24) are not neces-
sary, i.e., the process of solving the finite difference scheme for boundary value
problem (3.6) — (3.8) by the decomposition method may remain stable with
respect to the computing error if not all conditions from (3.22) — (3.24) are
satisfied.
According to Fig. 3.4c, the computing error of the solution can exceed 100 %
for large values of c.
Let us use substitution (3.27) for solving problem (3.44), (3.45).
218
3.7. Examples of the computing error. Instability and loss of accuracy
Fig. 3.4. Graphic results of solving problem (3.44), (3.45) by program Listing 3.4
for b = 1.5, l = 15 and the following values of c: 10 (a), 1017 (b), 1018 (c)
219
Chapter 3. Finite Difference Method for Solving Differential Equations
Substitution
x
u U ( x ) exp 0.5 g ( y ) dy
a
x
U ( x ) exp 0.5 cdy U ( x ) exp( 0.5cx ) (3.46)
0
into (3.44), (3.45) gives the following equation and boundary conditions:
d 2U
0.25c 2 U c exp(0.5cx ) , (3.47)
dx 2
U (0) 0 , U (b) b exp(0.5cb) . (3.48)
For boundary value problem (3.47), (3.48), it is easy to make sure that all the
conditions, formulated on p. 207, are satisfied when x ≥ 0, i.e., the decomposition
method is unconditionally stable.
The following program is used as the previous one.
Listing 3.5
Sub main()
Dim X() As Double
Dim G() As Double
Dim E() As Double
Dim F() As Double
Dim U() As Double
Dim c As Double, b As Double, l As Integer
Dim h As Double, i As Integer
c = Selection.Cells(1, 2)
b = Selection.Cells(2, 2)
l = Selection.Cells(3, 2)
h = b / l
ReDim X(5 To 5 + l)
ReDim G(5 To 5 + l)
ReDim E(5 To 5 + l)
ReDim F(5 To 5 + l)
ReDim U(5 To 5 + l)
For i = 5 To 5 + l
X(i) = (i - 5) * h
1: G(i) = 0
2: E(i) = -0.25 * c ^ 2
3: F(i) = c * Exp(0.5 * c * X(i))
220
3.7. Examples of the computing error. Instability and loss of accuracy
Next i
4: Call fb(5, 5 + l, h, 0, b * Exp(0.5 * c * b), _
G, E, F, U)
For i = 5 To 5 + l
Selection.Cells(i, 1) = X(i)
5: Selection.Cells(i, 2) = U(i) * _
Exp(-0.5 * c * X(i))
Next i
End Sub
Program Listing 3.5 solves boundary value problem (3.47), (3.48) and then
calculates the u (x) dependence by means of formula (3.46). This program dif-
fers from Listing 3.4 in operators 1 — 5.
Fig. 3.5 shows the results of using program Listing 3.5 at c = 10 and 20.
Unlike program Listing 3.4, program Listing 3.5 was not used at c = 1017 and
1018 because of exceeding 709.782712893 by the argument of the exponential
function in operator 3. In other words, according to Fig. 3.6, the stop of the exe-
cution of program Listing 3.5 would occur at c = 1017 and 1018 with the follow-
ing information: Run-time error ‘6’: Overflow.
According to the continuous and dashed lines in Fig. 3.5, we must reduce the
number of steps on segment [0, b] for improving the accuracy. According to the
dash-dotted line, the accuracy may be lost even when the computing process is
stable with respect to the computing error. We will speak about measures against
loss of accuracy also in section “Instead of Conclusions”.
221
Chapter 3. Finite Difference Method for Solving Differential Equations
Fig. 3.6. The Excel Help window with the Exp function description
It is natural to ask about the existence of a method for solving the finite dif-
ference scheme for boundary value problem (3.6) — (3.8), which is more stable
with respect to the computing error than the decomposition method used by us.
Before answering this question, we will consider several methods for solving the
system of linear algebraic equations of general form.
222
3.8. Solving the system of linear algebraic equations by using Excel functions
f1 x1
f2 x2
f , x .
... ...
fn xn
System (3.49) or, which is the same, matrix equation (3.51) can be solved by
means of Excel, without programming in VBA. Let us consider two methods of
the solution.
1. The solution of equation (3.51) can be written as x = A-1f, where A-1 is the
inverse A matrix (Section 1.21).
223
Chapter 3. Finite Difference Method for Solving Differential Equations
x1 x 12 , x 2 x 22 , ..., x n x 2n
... ... ...
x 1n x n2 x nn
are the solutions of the above n matrix equations and
x11 x 12 ... x 1n
224
3.9. Solving the system of linear algebraic equations by the Gaussian elimination method
225
Chapter 3. Finite Difference Method for Solving Differential Equations
where aij[ 2] aij ai1b1 j , fi[ 2] fi ai1 g1 , i = 2, ..., n, j = 2, ..., n. The index in
square brackets is the number of the current step of the forward course.
Let us assume that the a[222] coefficient is nonzero. Dividing both sides of the
1st equation of system (3.56) by this coefficient, we obtain equation
x2 b23 x3 ... b2 n xn g2 , (3.57)
a [22j] f 2[ 2 ]
where b2 j , g2 , j = 3, ..., n. The last equation is the result of the
a [222 ] a [222 ]
second step of the forward course.
To eliminate x 2 , we fulfill the same operations with equation (3.57) and sys-
tem (3.56) that we previously fulfilled with equation (3.55) and system (3.49).
Equation
xn gn , (3.58)
where g n f n[ n ] / a[nnn ] , is the result of the n-th step of the forward course.
226
3.9. Solving the system of linear algebraic equations by the Gaussian elimination method
Equations (3.55), (3.57) and (3.58) give the following system of linear alge-
braic equations:
x1 b12 x2 ... b1n xn g1 ,
x2 ... b2 n xn g2 ,
(3.59)
. . . . .
xn gn .
This system is the result of the forward course of the Gaussian elimination
method. We can write (3.59) in the form of matrix equation (3.53) with upper
triangular matrix (3.54).
The backward course consists in the determination of the unknown variables
by solving system (3.59). The following expressions are used:
1) according to the ultimate equation,
xn gn ;
2) according to the penultimate equation,
xn 1 gn 1 bn x ;
1, n n
3) according to the (n – 2)th equation,
xn 2 g n 2 bn 2, n x
1 n 1
bn x ,
2, n n
and so on.
An analysis of the forward course of the Gaussian elimination method shows
that it requires O( n 3 ) arithmetic operations, n . Similarly, the backward
227
Chapter 3. Finite Difference Method for Solving Differential Equations
Listing 3.6
Sub gaus(ByVal n, ByRef A() As Double, _
ByRef F() As Double, ByRef X() As Double)
Dim i As Integer, j As Integer, k As Integer
Dim AA() As Double: ReDim AA(1 To n, 1 To n)
Dim FF() As Double: ReDim FF(1 To n)
Dim B() As Double: ReDim B(1 To n, 1 To n)
Dim G() As Double: ReDim G(1 To n)
'Forward course:
For i = 1 To n
For j = 1 To n
AA(i, j) = A(i, j)
Next j
FF(i) = F(i)
Next i
For k = 1 To n - 1
For j = k + 1 To n
B(k, j) = AA(k, j) / AA(k, k)
Next j
G(k) = FF(k) / AA(k, k)
'end of step No. k
'beginning of step No. k + 1
For i = k + 1 To n
For j = k + 1 To n
AA(i, j) = AA(i, j) - AA(i, k) * _
B(k, j)
Next j
FF(i) = FF(i) - AA(i, k) * G(k)
Next i
228
3.10. Two subroutines for solving the system of linear algebraic equations
Next k
G(n) = FF(n) / AA(n, n)
'Backward course:
X(n) = G(n)
For k = n - 1 To 1 Step -1
X(k) = G(k)
For j = k + 1 To n
X(k) = X(k) - B(k, j) * X(j)
Next j
Next k
End Sub
of system (3.56) is processed, and so on. In this case, we say that the leading
coefficient is chosen in the column.
2. Renumbering the unknowns is performed to get the maximum element of
the first row of the system matrix as the leading coefficient. In this case, we say
that the leading coefficient is chosen in the row.
229
Chapter 3. Finite Difference Method for Solving Differential Equations
230
3.10. Two subroutines for solving the system of linear algebraic equations
19: AA(1, j) = w
20: Next j
21: w = FF(i_max)
22: FF(i_max) = FF(1)
23: FF(1) = w
24: For i = 1 To n
25: w = AA(i, j_max)
26: AA(i, j_max) = AA(i, 1)
27: AA(i, 1) = w
28: Next i
29: m = O(j_max)
30: O(j_max) = O(1)
31: O(1) = m
For k = 1 To n - 1
For j = k + 1 To n
B(k, j) = AA(k, j) / AA(k, k)
Next j
G(k) = FF(k) / AA(k, k)
'end of step No. k
'beginning of step No. k + 1
w = 0
For i = k + 1 To n
For j = k + 1 To n
AA(i, j) = AA(i, j) - AA(i, k) * _
B(k, j)
If Abs(AA(i, j)) > w Then
w = Abs(AA(i, j))
i_max = i
j_max = j
End If
Next j
FF(i) = FF(i) - AA(i, k) * G(k)
Next i
For j = k + 1 To n
w = AA(i_max, j)
AA(i_max, j) = AA(k + 1, j)
AA(k + 1, j) = w
Next j
w = FF(i_max)
FF(i_max) = FF(k + 1)
FF(k + 1) = w
For i = k + 1 To n
231
Chapter 3. Finite Difference Method for Solving Differential Equations
w = AA(i, j_max)
AA(i, j_max) = AA(i, k + 1)
AA(i, k + 1) = w
Next i
m = O(j_max)
O(j_max) = O(k + 1)
O(k + 1) = m
For i = 1 To k 'permuting columns of
'calculated part of array B
w = B(i, j_max)
B(i, j_max) = B(i, k + 1)
B(i, k + 1) = w
Next i
Next k
G(n) = FF(n) / AA(n, n)
'Backward course:
XX(n) = G(n)
For k = n - 1 To 1 Step -1
XX(k) = G(k)
For j = k + 1 To n
XX(k) = XX(k) - B(k, j) * XX(j)
Next j
Next k
32: For j = 1 To n
33: X(d + O(j)) = XX(j)
34: Next j
End Sub
ac 1, d
x
1 d 1
ac 1, d
x
2 d 2
... ac 1, d
x
n d n
fc 1
,
ac 2, d
x
1 d 1
ac 2, d
x
2 d 2
... ac 2, d
x
n d n
fc 2
,
. . . . . . . .
ac n, d
x
1 d 1
ac n, d
x
2 d 2
... ac n, d
x
n d n
fc n
,
where c and d are given integers. Such numbering is used in code Listing 6.15
(see operator 8 corresponding to n = c = d = 2).
232
3.10. Two subroutines for solving the system of linear algebraic equations
233
Chapter 3. Finite Difference Method for Solving Differential Equations
The forward and backward courses’ results, contained in the XX array, are the
calculated values of the unknowns. Operators 32 — 34 determine variables
xd 1 , xd 2 , ..., xd n by recovering the original numbering.
The gauss subroutine usage does not guarantee the solution of the system of
linear algebraic equations (3.49) because in general it may not exist if the D
determinant of matrix (3.50) is equal to 0: the division by D is performed in
Cramer’s rule (p. 202).
The gaus and gauss subroutines allow us to invert the A matrix. For that,
we must use formula (3.52), where B = A-1.
234
3.11. Reduction of the computing error
235
Chapter 3. Finite Difference Method for Solving Differential Equations
X(i) = (i - 5) * h
1: G(i) = c
2: E(i) = 0
3: F(i) = c
Next i
For i = 1 To n
For j = 1 To n
AA(i, j) = 0
Next j
Next i
AA(1, 1) = 1: AA(1, 2) = 0: FF(1) = 0
For i = 2 To n - 1
w = 0.5 * G(i + 4) * h
AA(i, i - 1) = 1 - w
AA(i, i) = E(i + 4) * h ^ 2 - 2
AA(i, i + 1) = 1 + w
FF(i) = F(i + 4) * h ^ 2
Next i
AA(n, n - 1) = 0: AA(n, n) = 1: FF(n) = b
4: Call gauss(n, AA, FF, XX)
For i = 5 To 5 + l
Selection.Cells(i, 1) = X(i)
Selection.Cells(i, 2) = XX(i - 4)
Next i
End Sub
236
3.11. Reduction of the computing error
In practice, the Gaussian elimination method is not used for the solution
of finite difference scheme (3.9), (3.11), (3.12) because of its inefficiency
(with respect to the execution time) for large values of n r k 1 .
When c → ∞ in problem (3.44), (3.45), the computing error of the solution
can be reduced in another way, without usage of the modernized Gaussian elimi-
nation method.
This alternative method for solving problem (3.44), (3.45) at large values of
c includes the following two stages:
1) changing formulation of the boundary value problem by excluding the
second derivative, u (x) , and one of the boundary conditions, u (0) 0 or
u(b) b ;
2) solving the resulting boundary value problem for the first-order linear
differential equation,
du
1.
dx
Thus, we should exercise caution in formulation of the problem and in choice
of the solution method.
237
Chapter 3. Finite Difference Method for Solving Differential Equations
d 2u du
F x, u , , (3.60)
dx 2 dx
238
3.12. Solving the nonlinear differential equation by the quasilinearization method
where y and z are increments of the second and third arguments of function
F ( x, y, z ) , 0 is the maximum of quantities | y | and | z | .
The solution of equation (3.60) can be written in the following form:
u ( x) u j ( x) v( x) ,
where u j (x) is the known j-th approximation of solution u (x ) , v (x ) is a small
quantity. By substituting this expression into equation (3.60), we obtain
d 2u j d 2v du j dv
F x, u j v, .
dx 2 dx 2 dx dx
or
d 2v dv
g ( x) e( x )v f ( x) , (3.62)
dx 2 dx
where
F du j
g ( x) x, u j , , (3.63)
z dx
F du j
e( x ) x, u j , , (3.64)
y dx
du j d 2u j
f ( x) F x, u j , . (3.65)
dx dx 2
Let u 0 ( x ) be the initial approximation of the solution of nonlinear differen-
tial equation (3.60), satisfying boundary conditions (3.7) and (3.8):
u 0 ( a ) A , u 0 (b ) B . (3.66)
In the quasilinearization method, the ( j 1 )th approximation of the u (x ) solu-
tion ( j = 0, 1, 2, ...) is calculated over the known j-th approximation as follows:
239
Chapter 3. Finite Difference Method for Solving Differential Equations
1) the values of functions g (x) , e(x ) and f (x) at the internal nodes of the
main grid on segment a ≤ x ≤ b (Fig. 3.1) are calculated according to formulas
(3.63) — (3.65);
2) second-order linear differential equation (3.62) with zero boundary condi-
tions v(a) v(b) 0 is solved by the decomposition method; function v (x ) is
the result;
3) the ( j 1 )th approximation of the u (x ) solution is calculated according
to formula
u j 1 ( x) u j ( x) v( x) .
The iterative process can be terminated under various conditions; we will use
the following:
max f ( x ) , (3.67)
a x b
where φ is a given positive constant, f (x) is function (3.65) tending to zero at
all points of segment [a, b] when j → ∞.
240
3.13. Solving the Shockley-Poisson equation
241
Chapter 3. Finite Difference Method for Solving Differential Equations
When the donor molecule loses an electron, it becomes positively charged; the
acceptor molecule losing a hole becomes negatively charged.
We can write equation (3.68) in form (3.60), where
q qy
F ( x, y , z ) N A ( x) N 0 exp .
k bT
Because of absence of the z variable in the right-hand side of this expression,
g (x) 0 in differential equation (3.62) according to (3.63). Expressions (3.64)
and (3.65) take the following form:
q2 qu j ( x )
e( x ) N 0 exp ,
k bT k bT
q qu j ( x) d 2u j
f ( x) N A ( x) N 0 exp .
k bT dx 2
According to the previous section, the solution of the boundary value prob-
lem for equation (3.68) is reduced to the repeated solution of linear differential
equation (3.62) with the above dependences, g (x) , e(x ) and f (x) , and with
boundary conditions v(a) v(b) 0 .
It was shown at the end of Section 3.3 that the process of solving such linear
problem by the decomposition method is unconditionally stable.
Let us consider table Listing 3.9 with the following source data for program
Listing 3.10:
coordinates a and b of the boundaries;
the value of φ in condition (3.67) for finishing the iterative process;
the values of dependences N A (x ) and u 0 ( x ) at the nodes of the uniform
grid on segment a ≤ x ≤ b (the number of grid nodes is equal to the number of
values of N A or u 0 in the table, that is, 11).
According to the table, the N A (x ) dependence is symmetric to the origin of
coordinates, x = 0. At the ends of segment [a, b] , the semiconductor contains
acceptors whose concentration is equal to 7·1020 m-3 = N A (a ) = N A (b ) = N 0 .
At the midpoint (x = 0), the semiconductor contains donors whose concentration
is equal to 3·1022 m-3 = N A ( 0) .
The initial approximation of the solution is calculated by means of Excel
according to formula
242
3.13. Solving the Shockley-Poisson equation
x
u0 ( x ) cos 1.
0.5 10 6
This u 0 ( x ) dependence satisfies boundary conditions (3.66) at A = B = 0.
Listing 3.9
a -5.00E-07
b 5.00E-07
phi 1.00E-01
NA u0
7.00E+20 0.00E+00
7.00E+20 1.91E-01
7.00E+20 6.91E-01
7.00E+20 1.31E+00
-3.00E+22 1.81E+00
-3.00E+22 2.00E+00
-3.00E+22 1.81E+00
7.00E+20 1.31E+00
7.00E+20 6.91E-01
7.00E+20 1.91E-01
7.00E+20 0.00E+00
The program below is intended for solving the boundary value problem for
the Shockley-Poisson equation by the quasilinearization method.
Listing 3.10
Sub main()
Dim NA() As Double
Dim U() As Double
Dim X() As Double
Dim U2() As Double
Dim V() As Double
Dim G() As Double
Dim E() As Double
Dim F() As Double
Dim m As Integer
Dim a As Double, b As Double
Dim phi As Double
Dim h As Double
Dim i As Integer, j As Integer
243
Chapter 3. Finite Difference Method for Solving Differential Equations
244
3.13. Solving the Shockley-Poisson equation
Next i
If max < phi Then Exit For
Next j
Selection.Cells(4, 4) = "u"
For i = 5 To m
Selection.Cells(i, 4) = U(i)
Next i
1: sb = Selection.Cells(5, 3).Address
2: se = Selection.Cells(m, 4).Address
3: sn = ActiveSheet.Name
4: Range(sb & ":" & se).Select
5: Selection.NumberFormat = "0.0E+00"
6: Charts.Add
7: ActiveChart.ChartType = xlXYScatterSmoothNoMarkers
8: ActiveChart.SetSourceData Source:= _
Sheets(sn).Range(sb & ":" & se), PlotBy:= _
xlColumns
9: ActiveChart.Location Where:= xlLocationAsObject, _
Name:=sn
10: ActiveChart.Axes(xlValue).MajorGridlines.Select
11: Selection.Delete
12: ActiveChart.Legend.Select
13: Selection.Delete
End Sub
245
Chapter 3. Finite Difference Method for Solving Differential Equations
Before the program execution, we must select the Excel table depicted in
Fig. 3.7. The execution results are as follows:
the coordinate and solution values located in the x and u columns, respec-
tively (Fig. 3.8);
the u (x) graph on the Excel worksheet.
Operators 1 — 13, intended for constructing the u (x) graph, were pro-
grammed by means of Excel Macro Recorder (Sections 2.4 and 2.5). Let us con-
sider the appointment of these operators.
Operator 1 assigns the address of the first cell of the x column (that is, string
"D6") to the sb variable; operator 2 assigns the address of the last cell of the u
column (that is, string "E16") to the se variable; operator 3 assigns the name of
the active Excel worksheet to the sn variable. Operator 4 selects the x and u
columns (that is, range D6:E16); operator 5 assigns the necessary numerical
format to the selected cells. Operators 6 — 9 construct the graph; they corre-
spond to the 2nd, 3rd and 4th operations on p. 214. Operators 10 and 11 delete
the gridlines from the graph area; operators 12 and 13 delete the legend.
246
3.13. Solving the Shockley-Poisson equation
247
Chapter 3. Finite Difference Method for Solving Differential Equations
Fig. 3.9. The realistic spatial distribution of the electric potential: the horizontal
coordinate, x, is in meters; the vertical coordinate, u, is in volts
248
3.14. Finite difference analogs of derivatives for a nonuniform grid
The execution time for solving the boundary value problem can be reduced
by replacing the uniform grid on [a, b] with a nonuniform grid whose step,
xi xi 1
hi , depends on i. At the transition to a nonuniform grid, expressions
(3.4) and (3.5) for the first and second derivatives of the u (x) function at node
xi become more complicated.
To obtain new expressions for the derivatives, we introduce axis z parallel to
the x axis (Fig. 3.10). If the origin of coordinates (z = 0) is at the xi node of the
grid, the xi 1
node has coordinate z hi , and the xi 1
node has coordinate
z hi 1
.
249
Chapter 3. Finite Difference Method for Solving Differential Equations
hi2 hi ui 1
ui ,
hi2 1
hi 1
ui 1
ui .
Solving this system of linear algebraic equations by Cramer’s rule [3], we obtain
D1 D2
, , (3.71)
D D
where
D hi hi 1 ( hi hi 1 ) ,
D1 (u i 1
ui ) hi (u i 1
ui ) hi 1
, (3.72)
D2 (ui 1
ui ) hi2 (ui 1
ui )hi2 1 .
Differentiating polynomial (3.70) twice, we obtain
dP
( z) 2 z , (3.73)
dz
d 2P
(z) 2 .
2
dz
From here, expressions for the derivatives at z = 0 follow:
dP D2 (u i 1
u i ) hi2 (u i 1
u i ) hi2 1
( 0) , (3.74)
dz D hi hi 1
( hi hi 1
)
d 2P D1 (u i 1
u i ) hi (u i 1
u i ) hi 1
( 0) 2 2 2 . (3.75)
dz 2 D hi hi (h
1 i
hi 1
)
We have the finite difference analogs of the first and second derivatives of
the u (x) function at the xi node.
Using expression (3.1), we can show the following:
250
3.14. Finite difference analogs of derivatives for a nonuniform grid
du (u i 1
u i ) hi2 (u i 1
u i ) hi2 1
hi hi 1 d 3u
( xi ) ( xi ) ... ,
dx hi hi 1
( hi hi 1
) 6 dx 3
2
d u (u i 1
u i ) hi (u i 1
u i ) hi 1
hi hi 1 d 3u
( xi ) 2 ( xi ) ...
dx 2 hi hi 1
( hi hi 1
) 3 dx 3
or
du (u i 1
ui ) hi2 (u i 1
ui ) hi2 1 2
( xi ) O( hmax ), (3.76)
dx hi hi (h
1 i
hi 1
)
d 2u (u i 1
ui ) hi (u i 1
ui ) hi 1
( xi ) 2 O( hmax ) , (3.77)
dx 2 hi hi (h
1 i
hi 1
)
where hmax max {hi } is the maximum step of the grid, hmax 0.
k 1 i r
The resulting expressions, (3.76) and (3.77), are similar to expressions (3.4)
and (3.5). Naturally, (3.76) and (3.77) become (3.4) and (3.5), respectively, for
the constant step ( hi hi 1 h ).
251
Chapter 3. Finite Difference Method for Solving Differential Equations
i
ei hi hi 1
g i ( hi hi 1
) 2,
hi ( 2 g i hi )
i
, (3.78)
hi hi 1
i
fi hi hi 1
.
252
3.15. The decomposition method for a nonuniform grid
253
Chapter 3. Finite Difference Method for Solving Differential Equations
254
3.16. Solving the Shockley-Poisson equation on a nonuniform grid
255
Chapter 3. Finite Difference Method for Solving Differential Equations
256
3.16. Solving the Shockley-Poisson equation on a nonuniform grid
Dim sn As String
Dim tm As Date
Const q = 1.6E-19
Const epsilon = 103.545E-12
Const kb = 1.38E-23
Const T = 300
m = Selection.Rows.Count 'quantity of rows
maxtime = Selection.Cells(1, 2)
maxiter = Selection.Cells(2, 2)
phi = Selection.Cells(3, 2)
ReDim NA(5 To m)
ReDim U(5 To m)
ReDim X(5 To m)
ReDim H(6 To m)
ReDim U2(5 To m)
ReDim V(5 To m)
ReDim G(5 To m)
ReDim E(5 To m)
ReDim F(5 To m)
w1 = q / epsilon
w2 = q / (kb * T)
For i = 5 To m
NA(i) = Selection.Cells(i, 1)
U(i) = Selection.Cells(i, 2)
X(i) = Selection.Cells(i, 3)
G(i) = 0
Next i
For i = 6 To m
H(i) = X(i) - X(i - 1)
Next i
If maxtime >= 0 And maxtime < 60 Then
tm = Now + TimeValue("00:00:" & CStr(maxtime))
End If
For j = 1 To maxiter
max = 0
For i = 6 To m - 1
w3 = NA(5) * Exp(-w2 * U(i))
E(i) = -w1 * w2 * w3
U2(i) = 2 * ((U(i + 1) - U(i)) * H(i) + _
(U(i - 1) - U(i)) * H(i + 1)) / _
(H(i) * H(i + 1) * (H(i) + H(i + 1)))
F(i) = w1 * (NA(i) - w3) - U2(i)
257
Chapter 3. Finite Difference Method for Solving Differential Equations
The source data for this program are the values of table Listing 3.12
(Fig. 3.11). Before the program execution, we have to select this Excel table
(range B2:D36, Fig. 3.12).
The execution results are the u solution values, which are located near the
corresponding values of the x coordinate, and the u (x) graph on the Excel work-
sheet (Fig. 3.13).
The u (x) graph is constructed automatically when executing operators 1 —
13. The same operators are present in program Listing 3.10.
258
3.16. Solving the Shockley-Poisson equation on a nonuniform grid
259
Chapter 3. Finite Difference Method for Solving Differential Equations
Fig. 3.13. The results of the program execution: the horizontal coordinate
of the graph, x, is in meters, the vertical coordinate, u, is in volts
260
3.17. Use of solution symmetry
hr2 u r 2
( hr2 1
2 hr 1 r
h hr2 ) u r 1
( hr2 1
2 hr 1 r
h ) ur
u (b )
hr h ( hr
1 r 1
hr )
or
261
Chapter 3. Finite Difference Method for Solving Differential Equations
ur 2
ur 1
ur , (3.79)
where
hr2 ,
hr2 1
2hr h
1 r
hr2 ,
hr2 1
2hr h ,
1 r
(3.80)
hr h ( hr
1 r 1
hr ) u (b) .
According to formula (3.13) for the backward sweep, we have
u r 1 Pr u r Qr ,
ur 2
Pr u
1 r 1
Qr 1
Pr 1
( Pr ur Qr ) Qr 1
.
Substituting these expressions into equation (3.79), we have
[ Pr 1
( Pr ur Qr ) Qr 1
] [ Pr ur Qr ] ur .
The solution of this equation follows:
( Pr 1
Qr Qr 1
) Qr
ur , (3.81)
Pr 1 r
P Pr
where , , and are defined by formulas (3.80).
Let us put the following declaration of the subroutine, which realizes the
decomposition method for differential equation (3.6) with u (b) given, into
Module6 of the BookNM workbook.
Listing 3.14
Sub forbac(ByVal k, ByVal r, ByRef X() As Double, _
ByRef G() As Double, ByRef E() As Double, _
ByRef F() As Double, _
ByVal GAMMAK, ByVal DELTAK, _
ByVal U1B, ByRef U() As Double)
Const BETAK = -2
Dim alpha As Double, beta As Double
Dim gamma As Double, delta As Double
Dim i As Integer, w As Double
Dim H() As Double: ReDim H(k + 1 To r)
Dim P() As Double: ReDim P(k + 1 To r)
Dim Q() As Double: ReDim Q(k + 1 To r)
For i = k + 1 To r
262
3.17. Use of solution symmetry
Formula (3.81) is used to start the backward sweep in the forbac subroutine.
The subroutine parameters have the following sense:
k, r are numbers of the left and right boundary nodes of the grid;
X is an array of grid nodes;
G, E are arrays of values of the coefficients of equation (3.6) at the grid
nodes;
F is an array of values of the right-hand side of equation (3.6);
GAMMAK, DELTAK are values of parameters k and k in left boundary
condition (3.11), where k
2;
U1B is a value of u (b) ;
263
Chapter 3. Finite Difference Method for Solving Differential Equations
0: Call forbac(5, m, X, G, E, F, 0, 0, 0, V)
5: Selection.NumberFormat = "0.000E+00"
The source data for this program are the values located in table Listing 3.15
(Fig. 3.14). We must select this Excel table (range B2:D21) before the program
execution.
Listing 3.15
maxtime 1
maxiter 1000
phi 1.00E-01
NA u0 x
7.00E+20 0.00E+00 -1.00E-05
7.00E+20 4.89E-02 -9.00E-06
7.00E+20 1.91E-01 -8.00E-06
7.00E+20 4.12E-01 -7.00E-06
7.00E+20 6.91E-01 -6.00E-06
7.00E+20 1.00E+00 -5.00E-06
7.00E+20 1.31E+00 -4.00E-06
7.00E+20 1.59E+00 -3.00E-06
7.00E+20 1.81E+00 -2.00E-06
7.00E+20 1.95E+00 -1.00E-06
7.00E+20 1.98E+00 -6.00E-07
7.00E+20 1.99E+00 -4.00E-07
7.00E+20 2.00E+00 -3.00E-07
7.00E+20 2.00E+00 -2.00E-07
-3.00E+22 2.00E+00 -1.00E-07
-3.00E+22 2.00E+00 0.00E+00
The results of the program execution are the u solution values and the u (x)
graph for negative values of x (Fig. 3.15).
According to the u (x) graph, semiconductor layer -6 μm ≤ x ≤ 6 μm, whose
plane is perpendicular to the x axis, is the potential well for signal electrons: this
layer collects electrons knocked out by photons (light particles) from semicon-
ductor molecules. The light falls on the layer plane.
In Section 4.7, the mathematical modeling of the silicon photosensitive target
will be continued, and we will use the resulting u (x) dependence depicted in
Fig. 3.15.
264
3.17. Use of solution symmetry
Fig. 3.15. The results of the program execution: the horizontal coordinate
of the graph, x, is in meters, the vertical coordinate, u, is in volts
265
Chapter 3. Finite Difference Method for Solving Differential Equations
266
3.18. The cyclic decomposition method
k
ek hr hk 1
g k ( hr hk 1
) 2,
hr (2 g k hr )
k
, (3.85)
hr hk 1
k
f k hr hk 1
.
267
Chapter 3. Finite Difference Method for Solving Differential Equations
k k
0 0 ... 0 0 k
k 1 k 1 k 1
0 ... 0 0 0
0 k 2 k 2 k 2
... 0 0 0
. . . . . . . .
0 0 0 0 ... r 2 r 2 r 2
r 1
0 0 0 ... 0 r 1 r 1
uk k
uk 1 k 1
uk 2 k 2
.
... ...
ur 2 r 2
ur 1 r 1
The matrix of this equation has the so-called cyclic tridiagonal form.
The system of equations (3.82) — (3.84), i.e., the above matrix equation,
is usually solved by the cyclic decomposition method. Let us consider this
algorithm.
Let y (x) , z (x) and u (x ) be grid functions defined on grid x k < xk 1
<
xk 2
< ... < xr 2
< xr 1
< x r (Fig. 3.1), and:
268
3.18. The cyclic decomposition method
i = k + 1, k + 2, ..., r – 2, r – 1,
zk zr 1 ; (3.89)
variables ui are the following linear combination of y i and zi :
ui yi u k zi , (3.90)
i = k, k + 1, k + 2, ..., r – 2, r – 1, r.
By substituting expression (3.90) into equations (3.83) and (3.84), we can
easily verify that grid function (3.90), u (x) , satisfies these equations at an arbi-
trary value of u k . Let us find the value of u k , at which grid function u (x) satis-
fies equation (3.82). For this purpose, we will consider the sweep formulas for
solution of systems (3.86), (3.87) and (3.88), (3.89).
Let formulas (3.18) and (3.13) of the backward sweep look like
yr 0 , zr 1 , (3.91)
yi 1
Pi yi Qi , zi 1
Pi z i Si , (3.92)
where i = r, r – 1, ..., k + 1. In this case, formulas (3.16), (3.17) and (3.14), (3.15)
of the forward sweep become
Pk 1 0 , Qk 1 0 , S k 1 1 , (3.93)
i i i
Qi S
i i
Pi 1
, Qi 1
, Si 1
, (3.94)
P
i i i i i
P i
P
i i i
where i = k + 1, k + 2, ..., r – 1.
By substituting expression (3.90) at i = r – 1 and i = k + 1,
ur 1 yr 1 uk z r 1 ,
uk 1
yk 1
uk zk 1
,
into equation (3.82), we obtain
k
( yr 1 u k z r 1 ) k k
u k
( yk 1
uk zk 1
) k
or
k k
yr 1 k
yk 1
uk . (3.95)
k
z
k r 1
z
k k 1
At this value of u k , the linear combination of grid functions y (x) and z (x) ,
defined by formula (3.90), satisfies not only equations (3.83) and (3.84), but also
equation (3.82).
According to the cyclic decomposition method, the system of linear algebraic
equations (3.82) — (3.84) is solved as follows:
269
Chapter 3. Finite Difference Method for Solving Differential Equations
270
3.19. Program realization of the cyclic decomposition method
271
Chapter 3. Finite Difference Method for Solving Differential Equations
272
3.20. Solving the oscillation equation
273
Chapter 3. Finite Difference Method for Solving Differential Equations
0
2 f0 2 / T0 .
In the presence of friction between the bar and horizontal surface, we observe
the oscillation damping. If the bar velocity is small, the friction force is propor-
tional to the bar mass, M, and to the first power of the bar velocity, du / dt . The
friction force is directed opposite to the velocity vector.
Taking into account the friction, we write the equation of Newton’s second
law as follows:
d 2u du
M Ku LM ,
dt 2 dt
It is obvious that after a while the oscillation of the bar becomes periodic
with period T .
Let us consider that time t changes from a negative value, t 0 , to infinity.
Let t1 be a negative value exceeding t 0 , such that:
t 0 ≤ t < t1 is an area of establishing the oscillation, in which the u (t )
solution is an aperiodic function;
t ≥ t1 is an area of the established oscillation, in which the u (t ) solution
is a periodic function with period T .
274
3.20. Solving the oscillation equation
Because the periodic oscillation of the bar is interesting for us, we consider
equation (3.96) on segment [0, T ] with the solution periodicity condition.
Equation (3.96) can be written in form (3.6),
d 2u du
g eu f (t ) , (3.97)
dt 2 dt
2
where g L , e 0
K / M , f (t ) F (t ) / M .
Let us consider the following source data table.
Listing 3.17
M 0.001
K 800
L 100
F t
0.00E+00 0.00E+00
0.00E+00 2.00E-03
0.00E+00 4.00E-03
0.00E+00 6.00E-03
0.00E+00 8.00E-03
0.00E+00 1.00E-02
0.00E+00 1.20E-02
0.00E+00 1.40E-02
0.00E+00 1.60E-02
0.00E+00 1.80E-02
0.00E+00 2.00E-02
0.00E+00 2.20E-02
0.00E+00 2.40E-02
0.00E+00 2.60E-02
5.00E+00 2.80E-02
1.00E+01 3.00E-02
5.00E+00 3.20E-02
0.00E+00 3.40E-02
0.00E+00 3.60E-02
0.00E+00 3.80E-02
0.00E+00 4.00E-02
0.00E+00 4.20E-02
0.00E+00 4.40E-02
0.00E+00 4.60E-02
0.00E+00 4.80E-02
0.00E+00 5.00E-02
275
Chapter 3. Finite Difference Method for Solving Differential Equations
In this table:
M is the bar mass in kilograms;
K is the elastic constant of the spring, in N / m;
L is the coefficient of the oscillation damping, in 1 / s;
t are the values of time for one period, in seconds;
F are the F (t ) function values in newtons.
According to table Listing 3.17:
1) every 0.05 seconds, a positive force acts on the bar, for example, it gets
a kick from left to right;
2) the maximum value of the force equals 10 N;
3) the duration of the force action equals 0.008 s.
The program for solving equation (3.97) under the periodicity condition is
given below.
Listing 3.18
Sub main()
Dim T() As Double
Dim G() As Double
Dim E() As Double
Dim F() As Double
Dim U() As Double
Dim m As Integer
Dim MM As Double
Dim KK As Double
Dim LL As Double
Dim i As Integer
Dim sb As String, se As String
Dim sn As String
m = Selection.Rows.Count 'quantity of rows
MM = Selection.Cells(1, 2)
KK = Selection.Cells(2, 2)
LL = Selection.Cells(3, 2)
ReDim T(5 To m)
ReDim G(5 To m)
ReDim E(5 To m)
ReDim F(5 To m)
ReDim U(5 To m)
For i = 5 To m
T(i) = Selection.Cells(i, 2)
G(i) = LL
E(i) = KK / MM
276
3.20. Solving the oscillation equation
F(i) = Selection.Cells(i, 1) / MM
Next i
0: Call forwback(5, m, T, G, E, F, U)
Selection.Cells(4, 3) = "u"
For i = 5 To m
Selection.Cells(i, 3) = U(i)
Next i
1: sb = Selection.Cells(5, 2).Address
2: se = Selection.Cells(m, 3).Address
3: Range(sb & ":" & se).Select
4: sn = ActiveSheet.Name
5: Selection.NumberFormat = "0.00E+00"
6: Charts.Add
7: ActiveChart.ChartType = xlXYScatterSmoothNoMarkers
8: ActiveChart.SetSourceData Source:= _
Sheets(sn).Range(sb & ":" & se), PlotBy:= _
xlColumns
9: ActiveChart.Location Where:= xlLocationAsObject, _
Name:=sn
10: ActiveChart.Axes(xlValue).MajorGridlines.Select
11: Selection.Delete
12: ActiveChart.Legend.Select
13: Selection.Delete
14: With ActiveChart
15: .Axes(xlCategory, xlPrimary).HasTitle = True
16: .Axes(xlCategory, _
xlPrimary).AxisTitle.Characters.Text = "t, s"
17: .Axes(xlValue, xlPrimary).HasTitle = True
18: .Axes(xlValue, _
xlPrimary).AxisTitle.Characters.Text = "u, m"
19: End With
20: ActiveChart.Axes(xlCategory).AxisTitle.Select
21: Selection.AutoScaleFont = True
22: With Selection.Font
23: .FontStyle = "regular"
24: .Size = 12
25: End With
26: ActiveChart.Axes(xlValue).AxisTitle.Select
27: Selection.AutoScaleFont = True
28: With Selection.Font
29: .FontStyle = "regular"
30: .Size = 12
277
Chapter 3. Finite Difference Method for Solving Differential Equations
278
3.20. Solving the oscillation equation
279
Chapter 3. Finite Difference Method for Solving Differential Equations
Fig. 3.19. The electrical circuit with the following parameters: electric
resistance R = 100 Ω, inductance L = 0.2 H, capacitance C = 3·10-4 F
280
Chapter 4.
Cubic Spline
281
Chapter 4. Cubic Spline
282
4.1. Definition of cubic spline. Spline moments
d 2S
( xi ) Mi ,
dx 2
where M i is the spline moment, k ≤ i ≤ r.
Let the spline moments, M i (k ≤ i ≤ r), be given (later we will know how to
calculate them). In this case, items (1) and (4) of the spline definition give
the following expression for the second derivative on elementary segment
[ xi 1 , xi ] :
xi x x xi 1
S ( x) Mi 1
Mi , (4.1)
hi hi
where hi xi xi 1
is the elementary segment’s length or the grid step, k + 1 ≤
i ≤ r.
Below, we will obtain expressions for the spline and its first derivative.
Let us integrate expression (4.1):
( xi x) 2 (x xi 1
)2
S ( x) Mi 1
Mi C1 , (4.2)
2hi 2hi
where C 1 is the integration constant.
Integrating expression (4.2), we have
283
Chapter 4. Cubic Spline
( xi x)3 (x xi 1
)3
S ( x) Mi 1
Mi C1 x C2 , (4.3)
6hi 6hi
where C 2 is the integration constant.
Integration constants C 1 and C 2 will be determined by means of item (2)
of the spline definition, according to which S ( xi ) f i and S ( xi 1
) fi 1
or
( xi xi 1
)3
xi C1 C2 fi Mi ,
6hi
( xi xi 1
)3
xi C
1 1
C2 fi 1
Mi 1
.
6hi
The solution of this system of two linear algebraic equations (with unknown
C 1 and C 2 ) has the following form:
fi fi 1
Mi Mi 1
C1 hi ,
hi 6
xi 1
xi hi hi
C2 fi fi 1
Mi xi 1
Mi 1
xi .
hi hi 6 6
By substituting the last two expressions for C 1 and C 2 into (4.3) and (4.2),
we obtain the following expressions for the spline and its derivative on segment
[ xi 1 , xi ] :
( xi x)3 (x xi 1
)3 Mi h2
1 i
xi x
S ( x) Mi 1
Mi fi 1
6hi 6hi 6 hi
M i hi2 x xi 1
fi , (4.4)
6 hi
( xi x) 2 (x xi 1
)2 fi fi 1
S ( x) Mi 1
Mi
2 hi 2 hi hi
Mi Mi 1
hi . (4.5)
6
284
4.1. Definition of cubic spline. Spline moments
( xi xi 1
)2 fi fi 1
Mi Mi 1
S ( xi 0) Mi hi , (4.6)
2hi hi 6
follows from (4.5).
Expression (4.5) for elementary segment xi ≤ x ≤ xi 1
looks like
( xi 1
x) 2 (x xi ) 2 fi 1
fi
S ( x) Mi Mi 1
2hi 1
2hi 1
hi 1
Mi 1
Mi
hi 1
. (4.7)
6
The expression for the spline derivative at point xi on the right,
( xi 1
xi ) 2 fi 1
fi Mi 1
Mi
S ( xi 0) Mi hi 1
, (4.8)
2hi 1
hi 1
6
follows from (4.7).
According to item (3) of the spline definition, the left and right derivatives
are equal:
S ( xi 0) S ( xi 0) .
By means of expressions (4.6) and (4.8), the last equality can be written as
follows:
hi h i hi 1 hi 1 fi 1 fi fi fi 1
Mi 1 Mi Mi 1 ,
6 3 6 hi 1 hi
where i = k + 1, k + 2, …, r – 2, r – 1 are the numbers of the interior grid nodes, or
i
Mi 1
2M i i
Mi 1 i
, (4.9)
where
hi
i
,
hi hi 1
285
Chapter 4. Cubic Spline
hi 1
i
1 i
, (4.10)
hi hi 1
fi 1
fi fi fi 1
hi 1
hi
i
6 .
hi hi 1
As the boundary conditions in item (5) of the spline definition, we will use
the following linear equations connecting the moments at the ends of segment
[a, b] :
2M k k
Mk 1 k
, (4.11)
r
Mr 1
2M r r
, (4.12)
where k
, k
, r
, r
are given parameters, k and r are numbers of the left and
right grid nodes; xk a and xr b.
If a given value of the function derivative on the left boundary, f k f (a ) , is
the condition in item (5), then (4.8) at i = k leads to the following expressions for
the parameters of equation (4.11):
6 fk 1
fk
k
1, k
fk . (4.13)
hk 1
hk 1
286
4.1. Definition of cubic spline. Spline moments
k
2, k
0 (4.17)
in equation (4.11).
The constancy of the second derivative at the right end of segment [a, b]
( Mr Mr 1
) leads to
r
2, r
0 (4.18)
in equation (4.12).
Expressions (4.13) — (4.18), as well as equations (4.11) and (4.12), may be
called spline boundary conditions.
Moments M k , M k 1 , M k 2 , ..., M r 2 , M r 1 , M r are determined by
solving the system of linear algebraic equations (4.9), (4.11) and (4.12). In this
case, the decomposition method (Section 3.2) can be used because forms (3.9),
(3.11) and (3.12) are available for equations (4.9), (4.11) and (4.12).
After calculating the moments, the values of the cubic spline and its first and
second derivatives at any point x of segment [a, b] can be calculated according
to formulas (4.4), (4.5) and (4.1), respectively.
The error of interpolating the f (x) function (and its derivatives) by the
S (x) spline (and by its derivatives) is determined by the following expression:
f ( n ) ( x) S ( n ) ( x) 4 n
O(hmax ), (4.19)
where hmax max {hi } is the maximum grid step ( hmax 0 ), n = 0, 1, 2,
k 1 i r
287
Chapter 4. Cubic Spline
288
4.2. Spline interpolation
'Backward sweep:
M(r) = (DELTAR - ALPHAR * Q(r)) / _
(ALPHAR * P(r) + 2)
For i = r To k + 1 Step -1
M(i - 1) = P(i) * M(i) + Q(i)
Next i
End Sub
The subroutine name (mos) occurs from “moments of spline”. The parame-
ters have the following sense:
k, r are numbers of the left and right boundary nodes of the grid on seg-
ment [a, b] ;
X is an array of grid nodes;
F is an array of the f (x) function values at the grid nodes;
GAMMAK, DELTAK correspond to k
and k
in left boundary condition
(4.11);
ALPHAR, DELTAR correspond to r
and r
in right boundary condition
(4.12);
M is an array intended for the spline moments.
The mos subroutine is based on the foba subroutine (Section 3.15).
In practice, not only the spline with boundary conditions (4.11) and (4.12) is
used, but also the periodic spline defined as follows.
Let f (x) be a periodic grid function with period Π b a :
f ( xi r k
) f ( xi ) ,
where xi r k
xi b a, i .
The periodic third-degree spline is function S (x) defined on the whole axis,
x , for which:
1) the first four conditions of the cubic spline definition (p. 282) are satisfied
on segment [a, b] ;
2) S ( xi r k
) S ( xi ) and S ( xi r k
) S ( xi ) for i .
We will use the periodic third-degree spline in Section 5.11, at that, we will
not calculate the moments of this spline. If the reader needs a subroutine for cal-
culating the moments of the periodic spline, its development is not a difficult
task: the forwback subroutine (Section 3.19), realizing the cyclic decomposi-
tion method, should be the basis for the new subroutine.
289
Chapter 4. Cubic Spline
290
4.2. Spline interpolation
This subroutine has 9 parameters, and the last two parameters, s1 and s2,
are optional. The parameters have the following sense:
k, r are numbers of the left and right boundary nodes of the grid on
segment [a, b] ;
X is an array of grid nodes;
F is an array of the f (x) function values at the grid nodes;
M is an array of the spline moments, for example, determined by the mos
subroutine execution;
chi is given point χ on [a, b] ;
s is a variable (memory cell) intended for the spline’s value at the χ point;
s1, s2 are variables respectively intended for the spline’s first and
second derivatives at the χ point.
In the si subroutine, cycle For…Next is used to find elementary segment
[ xi 1 , x i ] containing the χ point. After finding this segment, the spline’s value
is calculated according to formula (4.4), and, if needed, the spline’s first and
second derivatives are calculated according to (4.5) and (4.1), respectively.
291
Chapter 4. Cubic Spline
Transistors are the base elements of modern radio electronics. Two types of
transistors exist — bipolar and field-effect transistors. Both those and other such
elements are three-electrode devices based on semiconductors.
Let us consider a concrete example of using the cubic spline construction for
processing electrical characteristics of a field-effect transistor, and such, in which
the main carriers of electric current are electrons rather than holes.
The field-effect transistor electrodes are called source, drain and gate. With-
out delving into the device physics, we note the following regarding the elec-
trodes:
the source injects electrons into the semiconductor, the drain collects
these electrons, the gate regulates the electron flow;
by varying the electric potential difference between the gate and the
source, U gs , we change the drain current, I d .
The major electrical characteristics of the field-effect transistor are the output
current-voltage characteristics (OCVC) representing dependences of the drain
current, I d , on the potential difference between the drain and the source, U ds ,
for various values of U gs . Fig. 4.2 shows the OCVC calculated by means of
mathematical model [10] for electron-hole plasma in the transistor. The simula-
tion based on this model is quite time-consuming: the calculation of the I d value
(for given U gs and U ds ) can take hours on a personal computer.
In the bottom right corner of this book’s cover, we see the two-dimensional
distribution of electron concentration in the transistor for U gs = -3 V and U ds =
14 V. This picture, as well as the OCVC, is from article [10].
Listing 4.3 with tabular representation of the OCVC is given below. In this
table, as well as in Fig. 4.2, the values of potential differences are in volts, the
current is in milliamperes. We see that 18 cells of the table are empty. It is
because the I d value was not calculated for some values of U gs and U ds due
to economic reasons.
292
4.3. Use of cubic spline for processing transistor electrical characteristics
Uds Ugs 0 -1 -2 -3
0 0 0 0 0
0.2 94.5065 39.3361 0 0
0.4 179.9835 0 0
0.5 206.7334 45.3559 0 0
1 207.3824 49.0988 0 0
2 211.1779 55.4772 0 0
4 214.8481 66.276 0 0
6 217.707 76.2717 0 0
7.65 224.2229 0 0
8 0 0
8.35 89.793 0 0
9 0.809 0
10 242.0198 102.0164 5.1056 0
10.8 10.369 0
11 0
11.65 1.0724
12 266.5736 123.9969 22.674
13 37.3677 8.6525
14 298.5628 157.1723 58.0258 42.0182
293
Chapter 4. Cubic Spline
To build electrical circuits based on the above transistor, we must know the
parameters of its equivalent circuit. To determine these parameters by method
[11], the empty cells of the OCVC table should be filled beforehand. The pro-
gram given below allows doing it by means of the spline interpolation.
Listing 4.4
Sub main()
Dim X() As Double
Dim F() As Double
Dim MOM() As Double
Dim m As Integer, n As Integer
Dim g As Integer, d As Integer
Dim k As Integer, r As Integer
Dim s As Double
m = Selection.Rows.Count 'quantity of rows
n = Selection.Columns.Count 'quantity of columns
ReDim X(2 To n)
ReDim F(2 To n)
ReDim MOM(2 To n)
For g = 2 To m 'setting row number
'Formation of arrays X and F for row No. g:
For r = 2 To n
X(r) = Selection.Cells(1, r)
F(r) = Selection.Cells(g, r)
If F(r) <> 0 Then Exit For
Next r
k = r
For d = k + 1 To n
If Selection.Cells(g, d) <> 0 Then
r = r + 1
X(r) = Selection.Cells(1, d)
F(r) = Selection.Cells(g, d)
End If
Next d
'Calculating array MOM of moments for row No. g:
Call mos(2, r, X, F, 0, 0, 0, 0, MOM)
'Filling all cells of row No. g:
For d = 2 To n
Call si(2, r, X, F, MOM, _
Selection.Cells(1, d), s)
Selection.Cells(g, d) = s
Next d
294
4.3. Use of cubic spline for processing transistor electrical characteristics
Next g
End Sub
We enter this program into Module1 of the BookNM workbook. The source
data are the values given in table Listing 4.3. The program uses this table in the
transposed form (Fig. 4.3).
For transposing a matrix, Excel includes the TRANSPOSE function (p. 141),
which interprets the contents of empty cells as zero.
After using the TRANSPOSE function, we fulfill the following operations:
1) select the table shown in Fig. 4.3, which is the transposition result;
2) copy this table into Windows Clipboard, for example, by clicking on the
Copy button in the Clipboard area of the Home tab;
3) click on the Paste arrow;
4) in the Paste Values area of the open window, click on the left icon.
The table, depicted in Fig. 4.3, visually does not change. We must select this
table of the transistor characteristics (range B2:U6) before running program
Listing 4.4.
When executing the program, the g cycle parameter accepts the values of
2, 3, 4 and 5. Respectively, the cells of the 2nd, 3rd, 4th and 5th rows of the
selected table are being filled.
Let us consider arrays X and F at a fixed value of g. Before calling the mos
subroutine, arrays X and F contain the following values.
The F array begins with zero, i.e., F(2) = 0. The next elements of the F
array are the values of the g-th row (of the selected table), but not all: the zeros,
which are between the nonzero values, are eliminated. It is these zeros that filled
the empty cells of table Listing 4.3 upon its transposition by the TRANSPOSE
function.
295
Chapter 4. Cubic Spline
The X array contains the values of the 1st row (of the selected table), which
are located above the g-th row’s values included in the F array.
For example:
for fixed g = 2, array F contains the values of F(2) = 0, F(3) = 95,
F(4) = 180, F(5) = 207, F(6) = 207, F(7) = 211, F(8) = 215,
F(9) = 218, F(10) = 224, F(11) = 242, F(12) = 267, F(13) = 299,
and array X contains the values of X(2) = 0, X(3) = 0.2, X(4) = 0.4,
X(5) = 0.5, X(6) = 1, X(7) = 2, X(8) = 4, X(9) = 6, X(10) = 7.65,
X(11) = 10, X(12) = 12, X(13) = 14 (k = 2, r = 13);
for fixed g = 4, array F contains the values of F(2) = 0, F(3) = 0,
F(4) = 0, F(5) = 0, F(6) = 0, F(7) = 0, F(8) = 0, F(9) = 0, F(10) = 0,
F(11) = 0, F(12) = 0, F(13) = 1, F(14) = 5, F(15) = 10, F(16) = 23,
F(17) = 37, F(18) = 58, and array X contains the values of X(2) = 0,
X(3) = 0.2, X(4) = 0.4, X(5) = 0.5, X(6) = 1, X(7) = 2, X(8) = 4,
X(9) = 6, X(10) = 7.65, X(11) = 8, X(12) = 8.35, X(13) = 9,
X(14) = 10, X(15) = 10.8, X(16) = 12, X(17) = 13, X(18) = 14
(k = 2, r = 18).
For every value of g (2, 3, 4 and 5), the MOM array of the spline moments,
corresponding to arrays X and F, is calculated by means of the mos subroutine.
In the call of this subroutine, boundary conditions (4.15) and (4.16) are used,
where f f 0 . The values, being calculated when executing the si sub-
2 r( g )
routine, fill the cells of the g-th row of the table. Thus, zero or nonzero values
fill the cells with zeros of Fig. 4.3. Fig. 4.4 shows the program execution result.
Fig. 4.4. The transposed table of the transistor characteristics after the execution
After transposing the last table (Fig. 4.4) by means of the TRANSPOSE
function, we have table Listing 4.5, which is similar to Listing 4.3, but without
empty cells. Table Listing 4.5 can be used for calculating parameters of the tran-
sistor equivalent circuit by method [11].
296
4.3. Use of cubic spline for processing transistor electrical characteristics
Listing 4.5
The completed table of the transistor characteristics
Uds Ugs 0 -1 -2 -3
0 0 0 0 0
0.2 94.5065 39.3361 0 0
0.4 179.9835 47.336 0 0
0.5 206.7334 45.3559 0 0
1 207.3824 49.0988 0 0
2 211.1779 55.4772 0 0
4 214.8481 66.276 0 0
6 217.707 76.2717 0 0
7.65 224.2229 85.364 0 0
8 226.068 87.537 0 0
8.35 228.206 89.793 0 0
9 232.931 94.227 0.809 0
10 242.0198 102.0164 5.1056 0
10.8 250.805 109.515 10.369 0
11 253.214 111.626 12.04 0
11.65 261.644 119.291 18.554 1.0724
12 266.5736 123.9969 22.674 1.102
13 282 139.645 37.3677 8.6525
14 298.5628 157.1723 58.0258 42.0182
297
Chapter 4. Cubic Spline
According to the rules of integration and basic integrals [3], the integral of
polynomial (4.4) over segment [ xi 1 , xi ] equals
x
i fi 1
fi Mi 1
Mi
S ( x) dx hi hi3 .
x
2 24
i 1
Formulas (4.19) and (4.20) give the following estimation of the spline inte-
gration error:
b b
4
f ( x ) dx S ( x ) dx O( hmax ),
a a
298
4.4. Spline integration
The ios function returns (into the program) the value of the integral of
spline S(x) over segment [a, b] . Parameters k, r, X, F and M have the same
sense as the corresponding parameters of the si subroutine (p. 291). We will use
the ios function for solving the following task.
Table Listing 4.7 below is taken from Task 3.1 in book [8]. It contains the
mass of a vertically falling plastic foam ball (with radius equal to one inch) and
the results of measurement of its coordinate at different instants of time.
Listing 4.7
Experimental dependence of coordinate
of a falling ball versus time
Because of the air resistance, the ball movement differs from the movement
of a material point with the same mass, M = 0.000254 kg. To estimate this dif-
ference, we have to calculate the ball velocity at moment t = 0.8 s and compare it
with the corresponding velocity of the material point.
For solving this task, we use the laws of mechanics as follows:
according to the work-energy theorem, the change in kinetic energy of the
ball is equal to the work done by the forces acting on the ball, i.e., by the gravita-
tional and air resistance forces;
according to Newton’s second law, the resultant of the forces, acting on
d2y
the ball, is equal to the product of its mass, M, and acceleration, , which is
dt 2
a function of the y coordinate.
Thus, the change in kinetic energy of the ball (which will be calculated by a
program) is equal to
299
Chapter 4. Cubic Spline
b
W M y 2 ( y ) dy , (4.21)
a
where a = 0, b = 3.35,
d2y
y2 ( y ) . (4.22)
dt 2
Let us consider the following program for calculating the change in kinetic
energy of the ball.
Listing 4.8
Sub main()
Dim T() As Double
Dim Y() As Double
Dim Y2() As Double
Dim MOM() As Double
Dim m As Integer
Dim i As Integer
Dim W As Double
m = Selection.Rows.Count 'quantity of rows
ReDim T(3 To m)
ReDim Y(3 To m)
ReDim Y2(3 To m)
ReDim MOM(3 To m)
'Inputting dependence of coordinate Y versus time T:
For i = 3 To m
T(i) = Selection.Cells(i, 1)
Y(i) = Selection.Cells(i, 2)
Next i
'Calculating spline moments, i.e., acceleration Y2:
1: Call mos(3, m, T, Y, -2, 0, -2, 0, Y2)
'Calculating and outputting change in kinetic energy:
2: Call mos(3, m, Y, Y2, -2, 0, -2, 0, MOM)
3: W = Selection.Cells(1, 2) * ios(3, m, Y, Y2, MOM)
4: MsgBox "W =" & Str(Round(W, 6)) & " J"
End Sub
The source data for this program are the values given in table Listing 4.7
(Fig. 4.5). We have to select this Excel table before running the program.
The program contains two calls of the mos subroutine, operators 1 and 2.
In these calls, we use boundary conditions (4.17) and (4.18) for the constancy of
the spline moments at the left and right ends of segment [a, b] : M 3 M 4 and
300
4.4. Spline integration
Mm Mm 1
(m = 12). Operator 1 calculates the y2 ( y ) function values accord-
ing to formula (4.22). Operator 2 calculates array MOM of the spline moments,
which are used for integrating the y2 ( y ) function over [a, b] . Operator 3, con-
taining the call of the ios function, calculates the change in kinetic energy of
the ball according to formula (4.21). When executing operator 4, the calculated
value is rounded up to six decimal places and displayed in the standard window
(Fig. 4.6). To finish the program execution, we must click on the OK button in
this window.
301
Chapter 4. Cubic Spline
According to the program execution result (Fig. 4.6), the change in kinetic
energy of the ball is equal to
W 0.004542 J .
Because the material point’s acceleration is equal to the free fall acceleration,
g = 0.981 m / s2, the change in its kinetic energy on segment [a, b] is equal to the
following value:
Mg (b a) 0.008347 J .
Because of the zero value of the ball velocity at moment t = -0.132 s, the
ball’s kinetic energy at t = 0.8 s is equal to W:
MV2
W 0.004542 J .
2
This gives the following value of the ball velocity at moment t = 0.8 s:
2W
V 5.980 m / s .
M
The corresponding value for the material point is
2 Mg (b a )
V 8.107 m / s .
M
Thus, the air resistance plays an important role in the fall of the plastic foam ball.
To consolidate the material of this and the previous sections, we advise the
reader to write a program for calculating the average value of function f (x) on
segment [a, b] . Formula
b
1
f average f ( x ) dx
b a
a
and the cubic spline on uniform grid a x0 < x1 < x 2 < ... < xn 2
< xn 1
<
xn b must be used. The f (x) function is from Appendix 4; segment [a, b] is
this function’s domain.
302
4.5. Iterative methods for solving the nonlinear algebraic equation
Let nonlinear function f (x) and segment [u, v] be given with the following
properties:
function f (x) is continuous and monotonous on [u, v] ;
the function values on the left and right boundaries of segment [u, v]
have different signs.
We will consider nonlinear algebraic equation
f (x) 0 . (4.23)
It is obvious that this equation has one and only one solution on [u, v] . We have
to find this solution.
A segment containing a unique solution of equation (4.23), for example
[u, v] , is called the uncertainty segment.
Equation (4.23) can be solved by using the Solver add-in for Excel. Such
usage of Solver will be considered on an example of
f ( x) x cos x 1.5 . (4.24)
For this function, segment [0.5, 2.5] is the uncertainty segment (this is easily
verified).
We enter an initial approximation of the solution, for example 2, into cell G1.
Into cell F1, we enter formula
=G1-COS(G1)-1.5
303
Chapter 4. Cubic Spline
Fig. 4.7. The Excel worksheet before start of solving equation (4.23), (4.24)
Fig. 4.8. The Solver Parameters window before start of solving the equation
304
4.5. Iterative methods for solving the nonlinear algebraic equation
Fig. 4.9
Fig. 4.10. The Excel worksheet upon termination of solving the equation
305
Chapter 4. Cubic Spline
306
4.5. Iterative methods for solving the nonlinear algebraic equation
along the x axis when considering various cycles. In Section 6.2, the step-by-step
movement will be used to find the segment that contains the minimum point of
a nonlinear function of one variable.
The limitation of the bisection method is the same as for the Solver add-in:
the program realization of the method “must know” how to calculate the f (x)
value at an arbitrary value of x. Therefore, the program realization of the bisec-
tion method for tabular function f (x) will use the spline interpolation to deter-
mine the function value at any x value, i.e., for the function continuation.
We will solve the following task by the bisection method.
Time moments t (further, x) and corresponding values of coordinate y of the
vertically falling plastic foam ball are given in table Listing 4.7 from the previ-
ous section. We are interested in the T moment of time when the ball has a given
coordinate, for example Y = 1 m.
The desired value of T is the solution of equation (4.23), where
f ( x) y ( x) Y . (4.27)
Because y (x) is a grid function (defined by table Listing 4.7), f (x) determined
by (4.27) is a grid function too.
According to table Listing 4.7:
at u 0.3 and v 0.4 , segment [u, v] is the uncertainty segment;
fu y (0.3) 1 0.13 , f v y (0.4) 1 0.27 .
To solve equation (4.23), (4.27) by the bisection method, we will use the
cubic spline to determine the function value for any x value (for example,
x 0.35 ), i.e., for making the f (x) function continuous.
The following code is intended for determining moment T when the ball has
a given Y coordinate.
Listing 4.9
Dim ns As Long 'counter of calls
Dim m As Integer
Dim X() As Double
Dim F() As Double
Dim MOM() As Double
Sub main()
Dim s As String, Y As Double
Dim i As Integer
Dim u As Double, fu As Double
Dim v As Double, fv As Double
Dim w As Double, fw As Double
307
Chapter 4. Cubic Spline
308
4.5. Iterative methods for solving the nonlinear algebraic equation
The source data are given in table Listing 4.7 (Fig. 4.5). We must select this
Excel table before the code execution. A value of Y must be entered into the text
box of the standard window (see operators 1 and 2 and Fig. 4.11). Uncertainty
segment [ xi 1 , xi ] is determined by means of operator 4.
Fig. 4.11. The window with the coordinate of the falling plastic foam ball
309
Chapter 4. Cubic Spline
Further, equation (4.23), (4.27) is solved by the bisection method (see opera-
tors 6 and 7). In condition (4.26) for finishing the iterative process, the value of
is equal to a millionth part of the initial uncertainty segment’s length (see
operator 5).
In the iterative process, the segment subroutine is used for reducing the
uncertainty segment length (see operator 6). This subroutine is declared below
the main program.
When executing operator 8, the solution of equation (4.23), (4.27) is rounded
up to six decimal places and displayed in the standard window (Fig. 4.12):
T = 0.334042. The number of iterations is also displayed in this window; it
equals 20. We have to click on the OK button for finishing the execution of code
Listing 4.9.
Fig. 4.12. The window for the bisection method with the
calculated moment of time and the number of iterations
Let us use the secant method (instead of the bisection method) in the itera-
tive process of solving equation (4.23), (4.27). For that, formula (4.25) must be
replaced with the following:
(v u ) f v
w v . (4.28)
fv fu
For obtaining the last formula, let us consider the geometric interpretation of
the secant method depicted in Fig. 4.13. According to this figure, we can deter-
mine a new position ( x w ) of the uncertainty segment boundary (left or right)
as follows:
1) run the secant line through points (u, f u ) and (v, f v );
2) denote the coordinate of the crosspoint of this line with the x axis by w.
310
4.5. Iterative methods for solving the nonlinear algebraic equation
According to Fig. 4.13, the slope of the secant line, passing through points
(u, f u ) and (v, f v ), is equal to
fu fv
.
w u v w
This ratio leads to formula (4.28).
For replacing the iterative method in code Listing 4.9, we have to replace
operator 9 with the following:
Fig. 4.14 shows the result of executing the new version of code Listing 4.9 for
Y = 1. As we see, the number of iterations is reduced to 12 (from 20).
Let us consider the question of the convergence of the above iterative
processes defined by formulas (4.25) and (4.28). Starting with the bisection
method, we use the following designations:
j 1
w x ;
j
is u x or v x to get the same sign of j as the sign of j 1
defined above.
Here, j is the iteration number, x is the exact solution of the equation, that
is, f (x ) 0.
311
Chapter 4. Cubic Spline
Fig. 4.14. The window for the secant method with the
calculated moment of time and the number of iterations
The x location near any boundary of the initial uncertainty segment is the
worst situation for the convergence. In this case,
j 1 j
C , (4.29)
312
4.5. Iterative methods for solving the nonlinear algebraic equation
defined form with the CheckBox element (for choosing the method) must be the
user interface of the program. Segment [a, b] must be the initial uncertainty
segment.
In the next section, we will develop a noniterative method for solving the
nonlinear algebraic equation with grid function f (x) . In Section 5.5, we will
return to iterative methods for solving the nonlinear algebraic equation.
313
Chapter 4. Cubic Spline
3ac b 2 2b 3 bc d
where 3 p , 2q .
3a 2 27a 3 3a 2 a
2. The real roots of equation (4.33) are calculated, one or three (two of
which may coincide), and then the corresponding roots of equation (4.31) are
calculated.
For solving equation (4.33), we use the method represented in the table of
Appendix 5. For subsequent calculations of the real roots of equation (4.31), we
use formula (4.32).
3. The unique solution of equation (4.23), (4.27) is determined.
314
4.6. Noniterative method for solving the nonlinear algebraic equation
The declaration of the table subroutine, intended for calculating the real
roots of equation (4.31), follows:
Listing 4.10
Sub table(ByVal a, ByVal b, ByVal c, ByVal d, _
ByRef x() As Double)
Dim b3a As Double, p As Double, q As Double
Dim r As Double, gamma As Double, phi As Double
Const beta = 1 / 3, pi = 3.141592654
x(1) = 1E+308
x(2) = 1E+308
x(3) = 1E+308
If 27 * a ^ 3 = 0 Then Exit Sub 'if a = 0
b3a = b / (3 * a)
p = (3 * a * c - b ^ 2) / (3 * a ^ 2) / 3
q = (2 * b ^ 3 / (27 * a ^ 3) - b * c / _
(3 * a ^ 2) + d / a) / 2
r = Sgn(q) * Sqr(Abs(p))
If r ^ 3 = 0 Then 'if p = 0
x(1) = -Sgn(q) * Abs(2 * q) ^ beta - b3a
Exit Sub
End If
If q = 0 Then 'if q = 0
x(1) = - b3a
If p < 0 Then
x(2) = Sqr(-3 * p) - b3a
x(3) = -Sqr(-3 * p) - b3a
End If
Exit Sub
End If
gamma = q / r ^ 3 'gamma > 0
If p < 0 Then
If gamma <= 1 Then
phi = Atn(Sqr(1 - gamma ^ 2) / gamma)
x(1) = -2 * r * Cos(phi / 3) - b3a
x(2) = 2 * r * Cos((pi - phi) / 3) - b3a
x(3) = 2 * r * Cos((pi + phi) / 3) - b3a
Else
phi = Log(gamma + Sqr(gamma ^ 2 - 1))
x(1) = -2 * r * _
(Exp(phi / 3) + Exp(-phi / 3)) / 2 - b3a
End If
315
Chapter 4. Cubic Spline
Else
phi = Log(gamma + Sqr(gamma ^ 2 + 1))
x(1) = -2 * r * _
(Exp(phi / 3) - Exp(-phi / 3)) / 2 - b3a
End If
End Sub
The subroutine name (table) is due to the fact that the subroutine algorithm
is based on the table in Appendix 5. Let us enter declaration Listing 4.10 into
Module11 of the BookNM workbook.
The table subroutine parameters have the following sense:
a, b, c, d are coefficients a, b and c and constant term d of cubic equation
(4.31);
x is an array for real solutions (one or three; free elements of the x array
are assumed to be equal to 10308).
The following program is intended for determining the T moment when the
falling plastic foam ball (from the two previous sections) has a given Y coordi-
nate.
Listing 4.11
Sub main()
Dim s As String, Y As Double
Dim m As Integer
Dim X() As Double
Dim F() As Double
Dim MOM() As Double
Dim i As Integer, h As Double
Dim a1 As Double, a2 As Double
Dim b1 As Double, b2 As Double
Dim a As Double, b As Double
Dim c As Double, d As Double
Dim T As Double
Dim xxx(1 To 3) As Double, k As Integer
1: s = InputBox("Enter value of Y and click OK")
2: Y = Val(s)
m = Selection.Rows.Count 'quantity of rows
ReDim X(3 To m)
ReDim F(3 To m)
ReDim MOM(3 To m)
For i = 3 To m
X(i) = Selection.Cells(i, 1)
F(i) = Selection.Cells(i, 2) - Y
316
4.6. Noniterative method for solving the nonlinear algebraic equation
If F(i) = 0 Then
3: MsgBox "T =" & Str(Round(X(i), 6))
End
End If
Next i
If F(3) * F(m) > 0 Then
MsgBox "On boundaries of segment [" & _
CStr(X(3)) & ", " & CStr(X(m)) & "], " & _
vbCrLf & "function f(x) has identical signs"
End
End If
'Calculating spline moments:
Call mos(3, m, X, F, -2, 0, -2, 0, MOM)
'Searching uncertainty segment:
For i = 4 To m
4: If F(i - 1) * F(i) < 0 Then Exit For
Next i
'Forming cubic equation:
h = X(i) - X(i - 1)
a1 = MOM(i - 1) / (6 * h)
a2 = MOM(i) / (6 * h)
b1 = (F(i - 1) - MOM(i - 1) * h ^ 2 / 6) / h
b2 = (F(i) - MOM(i) * h ^ 2 / 6) / h
5: a = a2 - a1
6: b = 3 * a1 * X(i) - 3 * a2 * X(i - 1)
7: c = 3 * a2 * X(i - 1) ^ 2 - 3 * a1 * X(i) ^ 2 + _
b2 - b1
8: d = a1 * X(i) ^ 3 - a2 * X(i - 1) ^ 3 + _
b1 * X(i) - b2 * X(i - 1)
'Solving linear equation:
If 27 * a ^ 3 = 0 And 2 * b = 0 Then
9: T = -d / c
10: MsgBox "T =" & Str(Round(T, 6)) & _
vbCrLf & "- root of linear equation"
End
End If
'Solving quadratic equation:
If 27 * a ^ 3 = 0 Then
11: T = (-c + Sqr(c ^ 2 - 4 * b * d)) / (2 * b)
If X(i - 1) <= T And T <= X(i) Then
12: MsgBox "T =" & Str(Round(T, 6)) & _
vbCrLf & "- root of quadratic equation"
317
Chapter 4. Cubic Spline
End
End If
13: T = (-c - Sqr(c ^ 2 - 4 * b * d)) / (2 * b)
If X(i - 1) <= T And T <= X(i) Then
14: MsgBox "T =" & Str(Round(T, 6)) & _
vbCrLf & "- root of quadratic equation"
End
End If
End If
'Solving cubic or linear equation:
15: Call table(a, b, c, d, xxx)
If xxx(2) = 1E+308 Then
16: MsgBox "T =" & Str(Round(xxx(1), 6)) & _
vbCrLf & "- root of cubic equation"
End
End If
If X(i - 1) <= xxx(1) And xxx(1) <= X(i) _
And X(i - 1) <= xxx(2) And xxx(2) <= X(i) _
And X(i - 1) <= xxx(3) And xxx(3) <= X(i) Then
17: T = (F(i) * X(i - 1) - F(i - 1) * X(i)) / _
(F(i) - F(i - 1))
18: MsgBox "T =" & Str(Round(T, 6)) & _
vbCrLf & "- root of linear equation"
End
End If
For k = 1 To 3
If X(i - 1) <= xxx(k) And xxx(k) <= X(i) Then
19: MsgBox "T =" & Str(Round(xxx(k), 6)) & _
vbCrLf & "- root of cubic equation"
End
End If
Next k
End Sub
The source data are given in table Listing 4.7 (Fig. 4.5). We must select this
Excel table before the program execution. The value of Y must be entered into
the text box of the standard window (see operators 1 and 2 and Fig. 4.11).
Uncertainty segment [ xi 1 , xi ] is determined by means of operator 4.
Operators 5 — 8 calculate the coefficients and constant term of cubic equa-
tion (4.31) according to the following formulas:
a a2 a1 ,
318
4.6. Noniterative method for solving the nonlinear algebraic equation
b 3a1 xi 3a2 xi 1
,
c 3a2 xi2 1
3a1xi2 b2 b1 ,
d a1xi3 a2 xi3 1
b1xi b2 xi 1
,
where
Mi 1
Mi
a1 , a2 ,
6 hi 6 hi
Mi h2
1 i 1 M i hi2 1
b1 fi 1
, b2 fi .
6 hi 6 hi
For obtaining these formulas, we must transform expression (4.4) to the follow-
ing form:
S ( x ) ax3 bx2 cx d .
After determining a, b, c and d, the approximate solution of equation (4.23),
(4.27) is calculated by solving one of three algebraic equations — a linear, quad-
ratic or cubic equation.
1. The linear equation is solved if the resulting values of coefficients a and b
are equal to zero. Operator 9 calculates a root of equation cx d 0 according
to formula x d /c .
2. The quadratic equation is solved at the zero value of a ( b 0 ). Two roots
of equation bx2 cx d 0 are calculated by operators 11 and 13 according
to the well known formula [3],
x c c2 4bd /( 2b) .
319
Chapter 4. Cubic Spline
We advise the reader to write a program, similar to Listing 4.11, for solving
equation f (x) 0 on segment [a, b] by the noniterative method. In this equa-
tion, f (x ) is a function from Appendix 4; segment [a, b] is this function’s
domain. Uniform grid a x0 < x1 < x 2 < ... < xn 2
< xn 1
< xn b must
be used.
320
4.7. Calculating the charge storage capacity
Having studied the cubic spline construction, we will continue the modeling
of the silicon photosensitive target (Section 3.13).
It was mentioned on p. 264 that semiconductor layer -6 μm ≤ x ≤ 6 μm,
perpendicular to the x axis, is the potential well for signal electrons generated by
light falling on the layer plane. In this regard, an important electrical parameter
is the charge storage capacity of the target cell.
The charge storage capacity, Q max , is the signal electrons’ maximum charge
(in absolute value), which can be localized in the considered layer of unit area
(meter × meter).
The value of Qmax is calculated in the following five stages:
1) the moments of cubic spline S (x) , determined by the tabulated electric
charge density,
qu( x)
f ( x) q N 0 exp N A ( x) ,
kbT
321
Chapter 4. Cubic Spline
322
4.7. Calculating the charge storage capacity
Const T = 300
Dim w As Double, w1 As Double, w2 As Double
Dim i As Integer, h As Double
Dim a1 As Double, a2 As Double
Dim b1 As Double, b2 As Double
Dim a As Double, b As Double
Dim c As Double, d As Double
Dim e As Double
Dim xxx(1 To 3) As Double, k As Integer
m = Selection.Rows.Count 'quantity of rows
ReDim X(2 To m)
ReDim NA(2 To m)
ReDim U(2 To m)
ReDim F(2 To m)
ReDim MOM(2 To m)
w = q / (kb * T)
For i = 2 To m
NA(i) = Selection.Cells(i, 1)
X(i) = Selection.Cells(i, 3)
U(i) = Selection.Cells(i, 4)
Next i
For i = 2 To m
F(i) = q * (NA(2) * Exp(-w * U(i)) - NA(i))
Next i
'Calculating spline moments:
w = 6 * (F(3) - F(2)) / (X(3) - X(2)) ^ 2
w1 = 6 * (F(m - 1) - F(m)) / (X(m) - X(m - 1)) ^ 2
0: Call mos(2, m, X, F, 1, w, 1, w1, MOM)
'Searching uncertainty segment:
For i = 3 To m
4: If F(i - 1) * F(i) < 0 Then Exit For
Next i
'Forming cubic equation:
h = X(i) - X(i - 1)
a1 = MOM(i - 1) / (6 * h)
a2 = MOM(i) / (6 * h)
b1 = (F(i - 1) - MOM(i - 1) * h ^ 2 / 6) / h
b2 = (F(i) - MOM(i) * h ^ 2 / 6) / h
5: a = a2 - a1
6: b = 3 * a1 * X(i) - 3 * a2 * X(i - 1)
7: c = 3 * a2 * X(i - 1) ^ 2 - 3 * a1 * X(i) ^ 2 + _
b2 - b1
323
Chapter 4. Cubic Spline
8: d = a1 * X(i) ^ 3 - a2 * X(i - 1) ^ 3 + _
b1 * X(i) - b2 * X(i - 1)
'Solving linear equation:
If 27 * a ^ 3 = 0 And 2 * b = 0 Then
9: e = -d / c
GoTo 21
End If
'Solving quadratic equation:
If 27 * a ^ 3 = 0 Then
11: e = (-c + Sqr(c ^ 2 - 4 * b * d)) / (2 * b)
If X(i - 1) <= e And e <= X(i) Then GoTo 21
13: e = (-c - Sqr(c ^ 2 - 4 * b * d)) / (2 * b)
If X(i - 1) <= e And e <= X(i) Then GoTo 21
End If
'Solving cubic or linear equation:
15: Call table(a, b, c, d, xxx)
If xxx(2) = 1E+308 Then
16: e = xxx(1)
GoTo 21
End If
If X(i - 1) <= xxx(1) And xxx(1) <= X(i) _
And X(i - 1) <= xxx(2) And xxx(2) <= X(i) _
And X(i - 1) <= xxx(3) And xxx(3) <= X(i) Then
17: e = (F(i) * X(i - 1) - F(i - 1) * X(i)) / _
(F(i) - F(i - 1))
GoTo 21
End If
For k = 1 To 3
If X(i - 1) <= xxx(k) And xxx(k) <= X(i) Then
19: e = xxx(k)
GoTo 21
End If
Next k
'Calculating charge storage capacity:
21: Call si(2, m, X, F, MOM, e, w, w1, w2)
X(i - 1) = e
F(i - 1) = 0
MOM(i - 1) = w2
22: w1 = ios(i - 1, m, X, F, MOM) 'calculating Q1
23: w = Round(2 * w1, 4) 'calculating Qmax
24: MsgBox "Qmax = " & CStr(w) & " C/m^2"
End Sub
324
4.7. Calculating the charge storage capacity
The source data are the values given in table Listing 4.12 (Fig. 4.16). We
must select this table before running the program.
The program contains the call of the mos subroutine (operator 0) intended
for calculating the spline moments. In this call, conditions (4.13) and (4.14) are
used, corresponding to the zero value of the derivative on the left and right
boundaries of segment [a, 0] : f 2 f ( a ) 0 , f m f (0) 0 (m = 17).
The value of e is the result of solving equation S (x) 0 by the noniterative
method given in the previous section. Regarding the part that solves this equa-
tion, program Listing 4.13 is similar to program Listing 4.11. The solution of the
cubic equation is equal to e = -1.967·10-7 (we observed this value by using the
program debugger of Visual Basic Environment).
Operator 21 calculates the w2 value of the second derivative of the S (x)
spline at point x e by calling the si subroutine intended for the spline inter-
polation. Further, the w2 value is used (as the moment) when integrating S (x)
over segment [e, 0] .
325
Chapter 4. Cubic Spline
The calculated value of Qmax is of interest for designing both the photosensi-
tive target and elements of extraction of signal electrons stored in the target’s
cells: the considered device belongs to the class of charge transfer devices.
326
4.8. Subroutine for automatic creation of graphs
Further, we will use the graph creation subroutine whose declaration given
below must be put into Module12 of the BookNM workbook.
Listing 4.14
Sub graph(ByVal sb, ByVal se, ByVal sx, ByVal sy)
Dim wbOldSelection As Range
Set wbOldSelection = Selection
Range(sb & ":" & se).Select
Dim sn As String
sn = ActiveSheet.Name
Selection.NumberFormat = "0.00E+00"
Charts.Add
ActiveChart.ChartType = xlXYScatterSmoothNoMarkers
ActiveChart.SetSourceData Source:= _
Sheets(sn).Range(sb & ":" & se), PlotBy:= _
xlColumns
ActiveChart.Location Where:=xlLocationAsObject, _
Name:=sn
ActiveChart.Axes(xlValue).MajorGridlines.Select
Selection.Delete
ActiveChart.Legend.Select
Selection.Delete
With ActiveChart
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, _
xlPrimary).AxisTitle.Characters.Text = sx
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, _
xlPrimary).AxisTitle.Characters.Text = sy
End With
ActiveChart.Axes(xlCategory).AxisTitle.Select
Selection.AutoScaleFont = True
With Selection.Font
327
Chapter 4. Cubic Spline
.FontStyle = "regular"
.Size = 12
End With
ActiveChart.Axes(xlValue).AxisTitle.Select
Selection.AutoScaleFont = True
With Selection.Font
.FontStyle = "regular"
.Size = 12
End With
wbOldSelection.Select
End Sub
The parameters of the graph subroutine are the following four strings:
sb, se — the strings, which define the Excel range containing the argu-
ment and function values: sb is the address of the top left cell of the range; se is
the address of the bottom right cell;
sx, sy — the names of the horizontal and vertical axes, respectively.
In the parameter names:
letter “s” corresponds to word “string”;
“b” corresponds to word “beginning”;
“e” corresponds to word “end”;
“x” means the horizontal axis;
“y” means the vertical axis.
The basis of the graph subroutine are operators 1 — 32 of program
Listing 3.18. However, we see something new in the above subroutine, namely,
the selection recovery (pp. 173 and 174):
in the subroutine beginning, operator
wbOldSelection.Select
328
4.9. Cubic spline usage for solving the second-order linear differential equation
In Chapter 3, for solving the boundary value problem for the second-order
linear differential equation, we considered a method based on the solution ap-
proximation by the second-degree polynomial (Section 3.14). Below, for solving
the same problem, we will consider a method based on the solution approxima-
tion by the cubic spline.
As shown in Section 3.4, equation (3.6) can be written in form (3.30),
d 2U
E ( x )U F ( x) , (4.37)
dx 2
where E (x) and F (x) are given functions, U (x) is an unknown function. Con-
ditions (3.7) and (3.8) on the boundaries of segment [a, b] take form (3.33) and
(3.36),
A2 U ( a ) A1U ( a ) A3 , (4.38)
B2 U ( b ) B1U (b ) B3 , (4.39)
where A1 , A2 , A3 , B1 , B2 , B3 are given parameters.
We will develop a cubic spline method for solving the formulated boundary
value problem, (4.37) — (4.39), on the following grid familiar to us: a x k <
xk 1
< xk 2
< ... < xr 2
< xr 1
< xr b.
Let U k , U k 1
, Uk 2
, ..., U r 2
, Ur 1
, U r be the solution values at points
x k , xk 1
, xk 2
, ..., xr 2
, xr 1
, x r , respectively. The S (x) cubic spline
is considered whose graph passes through points ( x k , U k ), ( xk 1
, Uk 1
),
( xk 2
, Uk 2
), . . . , ( xr 2
, Ur 2
), ( xr 1
, Ur 1
), ( x r , U r ).
Because the spline moments are the values of S (x) at the grid nodes, equa-
tion (4.37) gives the following expression for the moment at the i-th node:
M i Fi EiU i , (4.40)
329
Chapter 4. Cubic Spline
where Fi and E i are the values of functions E (x) and F (x) at the i-th node,
k ≤ i ≤ r.
After replacing f i with U i in expression (4.10) for i , we have
Ui 1
Ui Ui Ui 1
hi 1
hi
i
. 6 (4.41)
hi hi 1
By substituting expressions (4.40) and (4.41) into (4.9), we obtain the follow-
ing equality:
6 6 6
i
Ei 1
Ui 1
2 Ei Ui
hi (hi hi 1
) hi 1
(hi hi 1
) hi (hi hi 1
)
6
i
Ei 1
Ui 1
F
i i 1
2 Fi F
i i 1
.
hi 1
(hi hi 1
)
Substituting expressions (4.10) for i
and i
, we get
hi 6
Ei 1
Ui 1
hi hi 1
hi (hi hi 1
)
6 6
2 Ei Ui
hi 1
( hi hi 1
) hi ( hi hi 1
)
hi 1 6
Ei 1
Ui 1
hi hi 1
hi 1
( hi hi 1
)
hi hi 1
Fi 1
2 Fi Fi 1
.
hi hi 1
hi hi 1
hi 1
( Ei h2
1 i
6)
i
,
3( hi hi 1
)
330
4.9. Cubic spline usage for solving the second-order linear differential equation
2
i
Ehh 2,
3 i i i 1
hi ( E i h2
1 i 1
6)
i
, (4.43)
3( hi hi 1
)
Fi h2h
1 i i 1 2 Fi h2 h
1 i 1 i
i
Fh h .
3( hi hi 1
) 3 i i i 1
3( hi hi 1
)
We write the boundary conditions in the following form similar to (3.11) and
(3.12):
2U k U
k k 1 k
, (4.44)
r
Ur 1
2U r r
, (4.45)
where k
, k
, r
, r
are given parameters.
To obtain formulas for calculating the values of k
and k
, we set i = k,
xk 1
xk hk 1
, fk 1
Uk 1
, fk U k in expression (4.8):
hk 1
Uk 1
Uk Mk 1
Mk
S ( xk 0) Mk hk 1
.
2 hk 1
6
Let us multiply both sides of the last equality by A1 and substitute expressions
Mk Fk EkU k ,
Mk 1
Fk 1
Ek 1
Uk 1
,
corresponding to (4.40) at i = k and i = k + 1. The following equality is the result:
h U Uk
A1S ( xk 0) A1 ( Fk EkU k ) k 1 A1 k 1
2 hk 1
Fk 1
Ek Uk
1 1
Fk EkU k
A1 hk 1
. (4.46)
6
Because U k U (a ) and S ( xk 0) U ( a ) , expression
A1S ( xk 0) A3 A2U k (4.47)
follows from (4.38).
Equating the right-hand sides of (4.46) and (4.47), we have
331
Chapter 4. Cubic Spline
hk 1
Uk 1
Uk
A3 A2U k A1 ( Fk EkU k ) A1
2 hk 1
Fk 1
Ek Uk
1 1
Fk EkU k
A1 hk 1
.
6
This equation can be written in form (4.44), where
( Ek h2
1 k 1
6) A1
k
, (4.48)
( Ek hk2 1
3) A1 3hk A
1 2
[(2 Fk Fk 1
)hk 1 1
A 6 A3 ]hk 1
k
. (4.49)
( Ek hk2 1
3) A1 3hk A
1 2
To obtain formulas for calculating the values of r
and r
in (4.45), we set
i = r, xr xr 1
hr , f r U r , fr 1
Ur 1
in (4.6):
hr Ur Ur 1
Mr Mr 1
S ( xr 0) Mr hr .
2 hr 6
Let us multiply both sides of the last equality by B1 and substitute expressions
Mr Fr E rU r ,
Mr 1
Fr 1
Er 1
Ur 1
,
corresponding to (4.40) at i = r and i = r – 1. The following equality is the result:
h U Ur 1
B1S ( xr 0) B1 ( Fr ErU r ) r B1 r
2 hr
Fr E rU r Fr 1
Er Ur
1 1
B1 hr . (4.50)
6
Because U r U (b ) and S ( xr 0) U (b) , expression
B1S ( xr 0) B3 B2U r (4.51)
follows from (4.39).
Equating the right-hand sides of (4.50) and (4.51), we have
h U Ur 1
B3 B2U r B1 ( Fr ErU r ) r B1 r
2 hr
332
4.9. Cubic spline usage for solving the second-order linear differential equation
Fr E rU r Fr 1
Er 1
Ur 1
B1 hr . (4.52)
6
This equation can be written in form (4.45), where
( Er h2
1 r
6) B1
r
, (4.53)
( E r hr2 3) B1 3hr B2
[(2 Fr Fr 1
) hr B1 6 B3 ]hr
r
. (4.54)
( E r hr2 3) B1 3hr B2
The system of linear algebraic equations (4.42), (4.44) and (4.45) is called the
cubic spline scheme for boundary value problem (4.37) — (4.39).
The values of unknown U k , U k 1 , U k 2 , ..., U r 2 , U r 1 , U r are deter-
mined by solving the formulated cubic spline scheme. In this case, the decompo-
sition method (Section 3.2) can be used because forms (3.9), (3.11) and (3.12)
are respectively available for equations (4.42), (4.44) and (4.45). Formulas
(4.48), (4.49) and k 2 are used in formulas (3.16) and (3.17) to start the
forward sweep. Formulas (4.53), (4.54) and r
2 are used in formula (3.18)
to start the backward sweep.
333
Chapter 4. Cubic Spline
334
4.10. Program realization of the cubic spline method for solving the linear differential equation
'Forward sweep:
w = (E(k) * h(k + 1) ^ 2 - 3) * A1 + _
3 * h(k + 1) * A2
gamma = (E(k + 1) * h(k + 1) ^ 2 + 6) * A1 / w
delta = ((2 * F(k) + F(k + 1)) * _
h(k + 1) * A1 + 6 * A3) * h(k + 1) / w
P(k + 1) = -gamma / 2
Q(k + 1) = delta / 2
For i = k + 1 To r - 1
w = 3 * (h(i) + h(i + 1))
alpha = h(i + 1) * _
(E(i - 1) * h(i) ^ 2 + 6) / w
beta = c * E(i) * h(i) * h(i + 1) - 2
gamma = h(i) * _
(E(i + 1) * h(i + 1) ^ 2 + 6) / w
delta = F(i - 1) * h(i) ^ 2 * h(i + 1) / w + _
c * F(i) * h(i) * h(i + 1) + _
F(i + 1) * h(i + 1) ^ 2 * h(i) / w
w = alpha * P(i) + beta
P(i + 1) = -gamma / w
Q(i + 1) = (delta - alpha * Q(i)) / w
Next i
'Backward sweep:
w = (E(r) * h(r) ^ 2 - 3) * B1 - 3 * h(r) * B2
alpha = (E(r - 1) * h(r) ^ 2 + 6) * B1 / w
delta = ((2 * F(r) + F(r - 1)) * _
h(r) * B1 - 6 * B3) * h(r) / w
U(r) = (delta - alpha * Q(r)) / _
(alpha * P(r) + 2)
For i = r To k + 1 Step -1
U(i - 1) = P(i) * U(i) + Q(i)
Next i
End Sub
335
Chapter 4. Cubic Spline
336
4.11. Solving the linear differential equation by the cubic spline method
To demonstrate the use of the cubic spline method described above, we will
solve equation (3.42) with boundary conditions (3.43). This boundary value
problem, concerning temperature characteristics of the radial flow between paral-
lel round disks, can be written in form (4.37) — (4.39), where
E ( x) 0.25x 4 (3c 1) x ,
F (x) 0 ,
A1 B1 B3 0,
A2 A3 B2 1.
As in Section 3.6, we consider that c = 10 and a ≤ x ≤ b, where a = 0, b = 1.5.
The program below is intended for solving the formulated problem by using
the fobas subroutine from the previous section.
Listing 4.16
Sub main()
Dim X() As Double
Dim E() As Double
Dim F() As Double
Dim U() As Double
Dim c As Double, b As Double, l As Integer
Dim h As Double, i As Integer
Dim sb As String, se As String
c = Selection.Cells(1, 2)
b = Selection.Cells(2, 2)
l = Selection.Cells(3, 2)
h = b / l
ReDim X(5 To 5 + l)
ReDim E(5 To 5 + l)
ReDim F(5 To 5 + l)
ReDim U(5 To 5 + l)
For i = 5 To 5 + l
X(i) = (i - 5) * h
337
Chapter 4. Cubic Spline
This main program is used similarly to programs Listing 3.2 and Listing 3.3
of Section 3.6:
the initial data are the values located in the table (Fig. 3.2a);
we must select this Excel table before the program execution (Fig. 3.2b).
Let us consider several operators of program Listing 4.16.
Operator 0 is the call of the fobas subroutine for solving boundary value
problem (3.42), (3.43) by the cubic spline method. The calculated values of the
solution, U (x) , are put into the U column (Fig. 4.18). The U (x) graph on the
Excel worksheet is created automatically when executing the graph subroutine
from Section 4.8; operator 1 is the subroutine call.
Operator 2 calculates solution u (x) of boundary value problem (3.39),
(3.40) by using formula (3.41). The calculated values of u (x) are put into the u
column (Fig. 4.18). The u (x) graph on the Excel worksheet is the result of the
second call of the graph subroutine (operator 3). This u (x) dependence is
close to u (x) depicted in Fig. 3.3.
338
4.11. Solving the linear differential equation by the cubic spline method
Fig. 4.18. The solutions of problems (3.42), (3.43) and (3.39), (3.40)
and the corresponding graphs (after their displacement by the mouse)
Note that one of the fobas parameters is the X array of grid nodes, i.e., this
subroutine is usable for both uniform and nonuniform grids. In this section, we
used a uniform grid; in the next section, a nonuniform grid will be used.
339
Chapter 4. Cubic Spline
Cables for geophysical works are intended for repeated descent of instru-
ments (fastened to the end of the cable) into a borehole and for electrical connec-
tion of these instruments with terrestrial equipment. By measuring the cable
length, the depth of the strata bedding can be determined. Single- and multi-
strand cables are used in practice.
Let us consider the cross section of an armored single-strand cable for geo-
physical works (Fig. 4.19).
340
4.12. Modeling of heating of a geophysical cable. Locally one-dimensional scheme
consists of seven copper wires, each of diameter 0.35 mm. This conductor is
covered with a 1.35 mm polymer layer for electrical insulation. A cotton layer
(which is an electrical insulator too) and double-layer armor (two zinced steel
wires) cover the polymer.
We will consider that the conductor is a copper wire of radius 0.5 mm
(0 ≤ x ≤ a in Fig. 4.20) and the insulator has the following three layers:
the 1.35 mm homogeneous polymer adjoins the central wire (a ≤ x ≤ r1 );
the 0.35 mm homogeneous cotton adjoins the armor ( r2 ≤ x ≤ b);
the 0.3 mm non-homogeneous material is placed between these two layers
( r1 < x < r2 ).
341
Chapter 4. Cubic Spline
where t is time, x is the radial coordinate, (x) is the thermal conductivity of the
insulator, c (x ) is the specific heat capacity, d (x) is the density of the insulator.
Because I 0 const , the temperature distribution does not depend on time,
u/ t 0 , and equation (4.55) becomes
d du
( x) x 0. (4.56)
dx dx
The boundary conditions are as follows:
du
(a) T (a) , (4.57)
dx
u (b) T (b) , (4.58)
where a, b are the inner and outer radii of the ring corresponding to the compli-
cated insulator (Fig. 4.20), T (a) is the derivative of temperature with respect
to x on the inner boundary of the ring, T (b) is the temperature on the outer
boundary.
To use the fobas subroutine from Section 4.10, we will transform boundary
value problem (4.56) — (4.58). For that, we use the following designation:
( x) x ( x) . (4.59)
Equation (4.56) takes form
d du
( x) 0.
dx dx
By differentiating the left-hand side of the last equation as the product of two
functions, (x) and du / dx , we can write this equation as follows:
d 2ud du
0.
dx2 dx dx
Dividing both sides by (x) , we have the following equation:
d 2u du
2
g ( x) 0, (4.60)
dx dx
where
d / dx
d ln
g ( x) . (4.61)
dx
Excluding the first derivative from equation (4.60) by substitution (3.27),
(a)
u ( x) U ( x) , (4.62)
( x)
342
4.12. Modeling of heating of a geophysical cable. Locally one-dimensional scheme
(b )
B3 T (b )
(a)
according to (3.34), (3.35), (3.37) and (3.38).
We need a formula that relates the electric current, I 0 , with the derivative of
temperature (with respect to x) on the inner boundary of the ring, T (a) .
To relate I 0 with T (a) , let us look at a piece of wire of length h. Geometri-
cally, this piece of wire is a right circular cylinder [3] of height h with the base
whose radius is equal to a.
According to the heat equation in integral form, the power of electric current
is equal to the heat flow through the lateral surface of the cylinder:
I 02 R (a)T (a) M , (4.65)
343
Chapter 4. Cubic Spline
where R is the electric resistance of the piece of wire, M is the lateral area of the
cylinder. Because
R h , M 2 ah,
a2
where is the resistivity of copper, equality (4.65) gives
I 02
T (a) . (4.66)
2 3
2 a (a)
Let us develop a program for calculation of overheating of the conductor and
insulator (in relation to the armor) caused by the I 0 current. This program will
use the source data table given below.
Listing 4.17
a 5.00E-04
I0 25
rho 1.78E-08
r1 1.85E-03
l1 10
lambda1 0.25
r2 2.15E-03
l2 5
b 2.50E-03
l3 5
lambda3 0.05
1
— the thermal conductivity of the homogeneous polymer, W / (m·K);
r2 — the outer radius of the non-homogeneous material, in meters;
l2 — the number of steps on segment r1 ≤ x ≤ r2 ;
344
4.12. Modeling of heating of a geophysical cable. Locally one-dimensional scheme
3
— the thermal conductivity of the homogeneous cotton, W / (m·K).
The u (x) dependence should be the main result of the program execution.
The program follows:
Listing 4.18
Sub main()
Dim x() As Double
Dim lambda() As Double
Dim mu() As Double
Dim ln_mu() As Double
Dim ln_mu1() As Double
Dim ln_mu2() As Double
Dim E() As Double
Dim F() As Double
Dim U() As Double
Dim a As Double, I0 As Double, rho As Double
Dim r1 As Double, l1 As Integer, lambda1 As Double
Dim r2 As Double, l2 As Integer
Dim b As Double, l3 As Integer, lambda3 As Double
Dim h1 As Double, h2 As Double, h3 As Double
Dim l As Integer, i As Integer
Dim T1a As Double, Tb As Double
Dim A1 As Double, A2 As Double, A3 As Double
Dim B1 As Double, B2 As Double, B3 As Double
Const pi As Double = 3.141592654
Dim w As Double
Dim sb As String, se As String
a = Selection.Cells(1, 2)
I0 = Selection.Cells(2, 2)
rho = Selection.Cells(3, 2)
r1 = Selection.Cells(4, 2)
l1 = Selection.Cells(5, 2)
lambda1 = Selection.Cells(6, 2)
r2 = Selection.Cells(7, 2)
l2 = Selection.Cells(8, 2)
b = Selection.Cells(9, 2)
l3 = Selection.Cells(10, 2)
lambda3 = Selection.Cells(11, 2)
345
Chapter 4. Cubic Spline
h1 = (r1 - a) / l1
h2 = (r2 - r1) / l2
h3 = (b - r2) / l3
l = l1 + l2 + l3
ReDim x(13 To 13 + l)
ReDim lambda(13 To 13 + l)
ReDim mu(13 To 13 + l)
ReDim ln_mu(13 To 13 + l)
ReDim ln_mu1(13 To 13 + l)
ReDim ln_mu2(13 To 13 + l)
ReDim E(13 To 13 + l)
ReDim F(13 To 13 + l)
ReDim U(13 To 13 + l)
'Definition of arrays x and lambda:
x(13) = a
lambda(13) = lambda1
For i = 14 To 13 + l1
x(i) = x(i - 1) + h1
lambda(i) = lambda1
Next i
For i = 14 + l1 To 13 + l1 + l2
x(i) = x(i - 1) + h2
lambda(i) = 0.5 * (lambda1 - lambda3) * _
Cos(pi * (x(i) - r1) / (r2 - r1)) + _
0.5 * (lambda1 + lambda3)
Next i
For i = 14 + l1 + l2 To 13 + l
x(i) = x(i - 1) + h3
lambda(i) = lambda3
Next i
Selection.Cells(12, 1) = "x"
Selection.Cells(12, 2) = "lambda"
For i = 13 To 13 + l
Selection.Cells(i, 1) = x(i)
Selection.Cells(i, 2) = lambda(i)
Next i
sb = Selection.Cells(13, 1).Address
se = Selection.Cells(13 + l, 2).Address
1: Call graph(sb, se, "x", "lambda")
'Definition of arrays mu, ln_mu, ln_mu1 and ln_mu2:
For i = 13 To 13 + l
mu(i) = lambda(i) * x(i)
346
4.12. Modeling of heating of a geophysical cable. Locally one-dimensional scheme
ln_mu(i) = Log(mu(i))
Next i
2: Call mos(13, 13 + l, x, ln_mu, _
0, -2 / a ^ 2, 0, -2 / b ^ 2, ln_mu2)
For i = 13 To 13 + l
3: Call si(13, 13 + l, x, ln_mu, ln_mu2, _
x(i), w, ln_mu1(i))
Next i
'Definition and solution of boundary value problem:
For i = 13 To 13 + l
E(i) = -0.25 * ln_mu1(i) ^ 2 - 0.5 * ln_mu2(i)
F(i) = 0
Next i
T1a = -I0 ^ 2 * rho / _
(2 * pi ^ 2 * a ^ 3 * lambda1)
Tb = 0
A1 = 1
A2 = -0.5 * ln_mu1(13)
A3 = T1a
B1 = 0
B2 = 1
B3 = Tb * Sqr(mu(13 + l) / mu(13))
4: Call fobas(13, 13 + l, x, E, F, A1, A2, A3, _
B1, B2, B3, U)
Selection.Cells(12, 3) = "x"
Selection.Cells(12, 4) = "u"
For i = 13 To 13 + l
Selection.Cells(i, 3) = x(i)
5: U(i) = U(i) * Sqr(mu(13) / mu(i))
Selection.Cells(i, 4) = U(i)
Next i
sb = Selection.Cells(13, 3).Address
se = Selection.Cells(13 + l, 4).Address
6: Call graph(sb, se, "x", "u")
Range("O36").Select
End Sub
The source data for this program are the values located in the Excel table
depicted in Fig. 4.21. We must select this table before the program execution.
Let us consider the main stages of the program execution.
After inputting the source data, the (x) function is defined in domain
[a, b] as follows:
347
Chapter 4. Cubic Spline
1
if a x r1
1 3
x r1 1 3
( x) cos if r1 x r2
2 r2 r1 2
3
if r2 x b
Operator 1 displays the (x) graph on the Excel worksheet (Fig. 4.22).
348
4.12. Modeling of heating of a geophysical cable. Locally one-dimensional scheme
349
Chapter 4. Cubic Spline
u~ ( x1 , x 2, j ) u (t , x1 , x 2, j ) d du~ ( x1 , x2, j )
cd , (4.68)
d x1 dx1
where u~ ( x1 , x 2 ) is an auxiliary function of two variables, x1, i and x2, j are the
coordinates of the gridlines (Fig. 4.23), indices i and j are the gridline numbers.
350
4.12. Modeling of heating of a geophysical cable. Locally one-dimensional scheme
351
Chapter 5.
Quadratic and Linear Splines
352
5.1. Definition of quadratic spline. Spline slopes
As in Section 4.1, let us consider segment [a, b] covered with grid a xk <
xk 1
< xk 2
< ... < xr 2
< xr 1
< xr b . Values f k , f k 1
, fk 2
, ...,
fr 2
, fr 1
, f r of grid function f (x) are given.
A quadratic spline (or second-degree spline, Fig. 5.1) is function P(x) ,
which satisfies the following conditions:
1) on each elementary segment xi 1 ≤ x ≤ xi (k + 1 ≤ i ≤ r), the spline
coincides with a second-degree polynomial (generally, the polynomials are
different on different elementary segments);
2) at the grid nodes, the spline has the grid function values: P ( xi ) fi ;
3) the spline has a continuous derivative, i.e., the spline is smooth;
4) on the left boundary of segment [a, b] , the spline satisfies an additional
condition (the boundary condition may be formulated on the right boundary).
353
Chapter 5. Quadratic and Linear Splines
354
5.1. Definition of quadratic spline. Spline slopes
hi ( xi x) 2 (x xi 1
)2
P( x) Qi 1
Qi fi 1
. (5.6)
2 2hi 2hi
According to item (4) of the quadratic spline definition, we define the slope
on the left boundary of segment [a, b] as follows:
Qk f (a ) ,
where f (a) is a given value of the function derivative on the left boundary.
Using recurrence formula (5.5) successively at i = k + 1, k + 2, ..., r, we can
calculate all slopes of the quadratic spline. Further, we can:
interpolate grid function f (x) by means of formula (5.6);
calculate the f (x) value at arbitrary point x of segment [a, b] by using
formula (5.1).
The error of interpolating the f (x) function (and its derivatives) by the
P(x) spline (and by its derivatives) is determined by the following expression:
f ( n ) ( x) P ( n ) ( x) 3 n
O(hmax ),
where hmax max {hi } is the maximum grid step ( hmax 0 ), n = 0, 1, 2
k 1 i r
355
Chapter 5. Quadratic and Linear Splines
356
5.2. Method for solving the initial value problem for the system of differential equations
hi
vi F ( xi , ui , vi ) , (5.10)
2
where
hi
ui 1
E ( xi 1
, ui 1
, vi 1
),
2
hi
vi F ( xi 1 , ui 1 , vi 1 ) .
1
2
Equations (5.9) and (5.10) form the system of algebraic equations with
respect to ui and vi (at known ui 1 and vi 1 ).
If u k u (a) A and vk v(a) Q are given, unknown functions u (x) and
v (x ) can be calculated at all grid nodes on segment [a, b] by solving the system
of algebraic equations (5.9) and (5.10) successively at i = k + 1, k + 2, ..., r.
As an example, we will solve the system of differential equations
du
v, (5.11)
dx
dv v2
(5.12)
dx 2 u
on segment [0, 1] . The initial conditions look like
u (0) A,
v(0) Q.
This initial value problem was solved in the fifth chapter of book [5] while
modeling a catalytic converter.
The catalytic converter is a device intended for lowering toxicity of waste
gases in the car exhaust system.
Let us write system (5.11), (5.12) in form (5.7), (5.8), where
E v,
v2
F .
2 u
We see that E is a linear function of variable v, F is a nonlinear function of
variables u and v.
Algebraic equations (5.9) and (5.10) take the following form:
357
Chapter 5. Quadratic and Linear Splines
hi
ui vi , (5.13)
2
hi vi2
vi , (5.14)
2 2 ui
where
hi
ui 1
vi 1
,
2
hi vi2 1
vi 1
.
2 2 ui 1
Let us solve the system of algebraic equations (5.13) and (5.14) for unknown
ui and vi .
Equation (5.13) can be written as
hi
ui
v . (5.15)
2 i
Multiplying both sides of equation (5.14) by 2 ui and substituting expression
(5.15) for ui , we obtain
(2 )
vi . (5.16)
hi
2
2
Formulas (5.16) and (5.15) allow us to calculate the values of vi and ui suc-
cessively at i = k + 1, k + 2, ..., r.
358
5.3. Program for solving the initial value problem
Let us develop a program for solving the initial value problem for the system
of differential equations (5.11) and (5.12). Number l = r – k of steps on segment
[0, 1] and the values of A and Q are given in the table below.
l 10
A 0.25
Q -0.1
359
Chapter 5. Quadratic and Linear Splines
h2 * beta)
u = alpha + h2 * v
Selection.Cells(i, 2) = u
Selection.Cells(i, 3) = v
Next i
End Sub
The program uses the values of the above table (Fig. 5.2). We must select this
Excel table before the program execution. The coordinates of the grid nodes and
the corresponding values of the u (x) and v (x ) dependences are placed in col-
umns x, u, v (Fig. 5.3).
360
5.3. Program for solving the initial value problem
We advise the reader to write a program (similar to Listing 5.1) for solving
the Bernoulli differential equation [3],
du
f ( x) u 2 ,
dx
on segment [a, b] under initial condition u(a ) 1 . In this equation, f (x ) is
a function from Appendix 4; segment [a, b] is this function’s domain.
361
Chapter 5. Quadratic and Linear Splines
In Section 5.6, we will need to solve the system of nonlinear algebraic equa-
tions
f1 ( x1 , x2 , ..., xn ) 1
,
f 2 ( x1 , x2 , ..., xn ) 2
, (5.17)
. . . . . .
f n ( x1 , x2 , ..., xn ) n
,
where ( x1j , x2j , ..., xnj ) x j is the j-th approximation of the x solution, z1 ,
z 2 , ..., z n are small quantities.
362
5.4. Solving the system of nonlinear algebraic equations by the Newton method
zmax max {| zi |} .
1 i n
f1 f1 f1
(x j ) ( x j ) ... (x j )
x1 x2 xn
a11 a12 ... a1n
f2 f2 f2
a 21 a 22 ... a 2 n (x j ) ( x j ) ... (x j )
x1 x2 xn (5.18)
. . . .
. . . .
a n1 an2 ... a nn
fn j
fn j
fn
(x ) ( x ) ... (x j )
x1 x2 xn
363
Chapter 5. Quadratic and Linear Splines
2) vector
b1 1
f1 ( x j )
b2 f 2 (x j )
2 (5.19)
... . . . .
bn
n
f n (x j )
is calculated;
3) the system of linear algebraic equations
a11 z1 a12 z 2 ... a1n z n b1 ,
a 21 z1 a 22 z 2 ... a 2n z n b2 ,
(5.20)
. . . . . . . . .
a n1 z1 an2 z 2 ... a nn z n bn
Various conditions can be applied for finishing the iterative process; we will
use the following:
zmax , (5.22)
364
5.5. Newton and Newton-like methods for solving the single nonlinear algebraic equation
It is obvious that the Newton iterative process of the previous section can be
used for solving not only the system of nonlinear algebraic equations, but also
for solving one equation, which can be considered as a system containing one
equation with respect to x1 :
f1 (x1 ) 1
.
In this case, the Newton method has a simple geometric interpretation.
The geometric interpretation will be considered on an example of equation
(4.23),
f (x) 0 ,
satisfying the following conditions in the f (x) function’s domain:
the f (x) function is continuous and monotonous;
the derivative, f (x) , is continuous, i.e., the f (x) function is smooth;
f (x) is different from 0;
the equation solution, x , exists.
In addition, we suppose that the solution’s initial approximation ( x 0 , which must
be given) is located in the f (x) function’s domain.
The Newton iterative process, defined by items (1) — (4) of the previous sec-
tion, can be written as follows:
f (x j )
xj 1
xj , (5.23)
f (x j )
where x j , x j 1
are the j-th and ( j 1 )th approximations of the equation solu-
tion, j = 0, 1, 2, ... Initial approximation x 0 is given.
Fig. 5.4 gives the geometric interpretation of the process of solving equation
f (x) 0 . According to this figure, the ( j 1 )th approximation of the x solu-
tion can be determined as follows:
1) restore the perpendicular to the x axis from point x j ;
365
Chapter 5. Quadratic and Linear Splines
2) run the tangent line through the point of intersection of the perpendicular
with the f (x) graph;
3) consider the coordinate of the point of intersection of the tangent line with
the x axis as the ( j 1 )th approximation of the equation solution, x j 1 .
This algorithm follows from formula (5.23) and the following property of the
tangent line passing through the point with coordinates x j and f ( x j ) : the slope
of this tangent line is equal to
f (x j )
f (x j ) .
xj xj 1
Due to the above geometric interpretation of the Newton method, it is also
called the tangent method.
In Section 4.5, equation (4.23), (4.24) of form x cos x 1.5 0 was solved
by using the Solver add-in for Excel. Below is a code for solving this equation
by the tangent method.
Listing 5.2
Sub main()
Dim j_lim As Integer
Dim zeta As Double
Dim x As Double
366
5.5. Newton and Newton-like methods for solving the single nonlinear algebraic equation
Dim f As Double
Dim a As Double
Dim j As Integer
Dim z As Double
1: j_lim = Range("I1").Value
2: zeta = Range("H1").Value
3: x = Range("G1").Value
For j = 1 To j_lim 'Newton iterations
4: Call f_function(x, f)
5: Call fx_jacobian(x, a)
6: z = -f / a
7: x = x + z
8: If Abs(z) < zeta Then Exit For
Next j
9: Range("G2").Value = x
10: Range("F2").Value = f
11: Range("E2").Value = a
12: Range("I2").Value = j
End Sub
In this code:
1) j_lim is the limiting number of iterations; its value is taken from cell I1
of the active worksheet (operator 1);
2) zeta is constant in condition (5.22) of finishing the Newton iterative
process; its value is taken from cell H1 (operator 2);
3) x is the current approximation of the equation solution; the initial value of
x (the initial approximation of the solution) is taken from cell G1 (operator 3).
After inputting the values of j_lim, zeta and x, the j cycle of the Newton
iterations is performed. In this cycle:
1) operator 4 calculates value f of the function according to formula
f ( x) x cos x 1.5 by calling the f_function subroutine;
367
Chapter 5. Quadratic and Linear Splines
Let us consider the question of the convergence of the Newton iterative pro-
cess defined by formula (5.23). For that, we use the following designation (simi-
lar to the designations on p. 311): x j x j
, where x is the exact solution
j
of the equation, i.e., f (x ) 0 . Let be a small quantity.
Substituting expressions x j x j
and x j 1
x j 1
into formula
(5.23), we have
f (x j)
j 1 j
.
f (x j)
j j
Let us use expressions similar to (3.1) for f ( x ) and f ( x ) and
f (x ) j f ( x ) O [( j )2 ]
368
5.5. Newton and Newton-like methods for solving the single nonlinear algebraic equation
j f ( x ) 0.5( j )2 f ( x ) O [( j )3 ]
j
f (x ) j f ( x ) O [( j )2 ]
0.5 j f (x ) O [( j )2 ] j)
j j 2 0.5 f ( x ) O(
( ) .
f (x ) j f (x ) O [( j )2 ] j)
f (x ) O (
j
Neglecting O ( ) in the numerator and denominator, we have the following
formula:
j 1 f (x ) j 2
0.5 ( ) . (5.24)
f (x )
Because f (x ) 0 , the last formula shows that the Newton iterative process
has quadratic convergence.
The secant method (Section 4.5), defined by formula (4.28) in form
(x j xj 1) f (x j )
xj 1
xj , (5.25)
f (x j ) f (x j 1)
369
Chapter 5. Quadratic and Linear Splines
j 1 f (x ) j j 1
0.5 . (5.26)
f (x )
The derivation of this formula is similar to the above derivation of (5.24). For-
mula (4.30) is the simplified form of (5.26).
at f ( x j ) 0.
Unlike the previous Newton-like method, the Steffensen method needs only
one initial approximation of the equation solution, x 0 .
370
5.5. Newton and Newton-like methods for solving the single nonlinear algebraic equation
Fig. 5.7 shows the possibility of cycling the Newton iterative process without
convergence to solution x if not all conditions, formulated at the beginning of
this section, are satisfied (set j = 0 in Fig. 5.7). If the Newton method is used for
solving the system of nonlinear algebraic equations (5.17), the cycling is also
possible.
Fig. 5.7. Cycling the iterative process of the Newton (tangent) method
371
Chapter 5. Quadratic and Linear Splines
In Section 5.2, we considered a method for solving the initial value problem
for the system of two first-order differential equations, (5.7) and (5.8). However,
the solution method does not change if the number of the system equations is
greater than two, as in the initial value problem below.
Article [12] considers a series of mathematical models of the piano mecha-
nism linking a key with hammer. We will use the model of medium complexity,
in which the key and hammer motion is described by the following system of
second-order differential equations:
d 2 u1
E2 (u1 , u3 ) , (5.27)
dt 2
d 2u3 du3
E 4 u1 , u 3 , , (5.28)
dt 2 dt
where
f k (u1 u3 )
E2 (u1 , u3 ) , (5.29)
m1
2
du3
q k (u1 u3 )
du3 dt
E 4 u1 , u 3 , . (5.30)
dt p qu3
In this model, u1 is the key’s displacement downward, u 3 is the hammer’s
displacement forward, f is the force acting on the key, k is the elastic constant
of the spring, m1 is the key’s mass, p and q are given constants, p qu3 m3 is
the hammer’s mass depending on its displacement (more exactly, m 3 is the
hammer’s effective mass).
We have to develop a code for solving this system of differential equations
on the time segment, 0 ≤ t ≤ b, with the following zero initial conditions:
372
5.6. Modeling of the piano mechanism linking a key with hammer
du1 du3
u1 (0) ( 0) u3 (0) ( 0) 0.
dt dt
Let us introduce the key and hammer velocities, u 2 and u 4 respectively, as
follows:
du1
u2 ,
dt
du3
u4 .
dt
The system of equations (5.27) and (5.28) takes the following form:
du1
E1 (u2 ) ,
dt
du 2
E2 (u1 , u3 ) ,
dt
du3
E3 ( u4 ) , (5.31)
dt
du4
E 4 (u1 , u 3 , u 4 ) ,
dt
where
E1 u2 ,
f k (u1 u3 )
E2 ,
m1
E3 u4 , (5.32)
qu 42 k ( u1 u3 )
E4 .
p qu3
The initial conditions become
u1 (0) u2 (0) u3 ( 0 ) u 4 ( 0) 0. (5.33)
As in Section 5.2, we construct the grid on segment 0 ≤ t ≤ b for solving the
formulated initial value problem and consider functions u1 (t ) , u 2 (t ) , u 3 (t ) ,
u 4 (t ) at the grid nodes. The grid step is assumed constant: b / l , where l is
a given number of time steps.
373
Chapter 5. Quadratic and Linear Splines
Let t i be the coordinate of a node, which is not the initial time moment,
i.e., 1 ≤ i ≤ l. To calculate the values of u1 (t ) , u 2 (t ) , u 3 (t ) , u 4 (t ) over known
values of u1 (t ) , u 2 (t ) , u 3 (t ) , u 4 (t ) , we must solve the following
system of nonlinear algebraic equations:
u1 (t ) E1[u2 (t )] u1 (t ) E1[u2 (t )] ,
2 2
u 2 (t ) E2 [u1 (t ), u3 (t )] u2 (t ) E2 [u1 (t ), u3 (t )] ,
2 2
u3 (t ) E3[u4 (t )] u3 (t ) E3[u4 (t )] ,
2 2
u4 (t ) E4 [u1 (t ), u3 (t ), u4 (t )]
2
u4 (t ) E4 [u1 (t ), u3 (t ), u4 (t )] .
2
After designations
u1 (t ) E1[u2 (t )] 1
,
2
u 2 (t ) E2 [u1 (t ), u3 (t )] 2
,
2
u3 (t ) E3 [u4 (t )] 3
, (5.34)
2
u 4 (t ) E4 [u1 (t ), u3 (t ), u4 (t )] 4
,
2
we can write this system of nonlinear algebraic equations in form (5.17) at n = 4:
f1 ( x1 , x2 , x3 , x4 ) 1
,
f 2 ( x1 , x2 , x3 , x4 ) 2
,
f 3 ( x1 , x2 , x3 , x4 ) 3
, (5.35)
f 4 ( x1 , x2 , x3 , x4 ) 4
,
where x1 u1 (t ) , x2 u 2 (t ) , x3 u3 (t ) , x4 u 4 (t ) .
According to expressions (5.32), we have
374
5.6. Modeling of the piano mechanism linking a key with hammer
f1 x1 E1 ( x2 ) x1 x2 ,
2 2
f k ( x1 x3 )
f2 x2 E2 ( x1 , x3 ) x2 ,
2 2 m1
f3 x3 E3 ( x4 ) x3 x4 , (5.36)
2 2
qx42 k ( x1 x3 )
f4 x4 E4 ( x1 , x3 , x4 ) . x4
2 2 p qx3
For solving the system of nonlinear algebraic equations (5.35) by the Newton
method, we need expressions for the partial derivatives of functions f1 , f 2 , f 3 ,
f 4 with respect to arguments x1 , x 2 , x 3 , x 4 , i.e., for the elements of Jacobian
matrix (5.18). By using the basic rules of differentiation [3], we obtain
f1 f1 f1 f1
1, , 0,
x1 x2 2 x3 x4
f2 k f2 f2 k f2
, 1, , 0,
x1 2m1 x2 x3 2m1 x4
f3 f3 f3 f3
0, 1, , (5.37)
x1 x2 x3 x4 2
f4 k f4
, 0,
x1 2 p qx3 x2
f4 k( p qx3 ) [ qx42 k ( x1 x3 )] q f4 qx 4
. , 1
x3 2 x4 p qx3
( p qx3 ) 2
Let us develop a code for solving the system of differential equations (5.31)
with initial conditions (5.33). In table Listing 5.3 with the source data for the
required code:
l is the number of time steps;
τ is the time step in seconds;
f is the force acting on the key, in newtons;
m1 is the key’s mass in kilograms;
375
Chapter 5. Quadratic and Linear Splines
As results of the execution, we must have the values of time t and the corre-
sponding values of the key’s and hammer’s displacements and velocities, i.e., we
du1 du3
must have u1 , u2 , u 3 , u4 as functions of time t.
dt dt
Below are the main program and the e_functions and fx_jacobian
subroutines for solving the initial value problem.
Listing 5.4
Dim tau As Double
Dim f As Double, m1 As Double
Dim p As Double, q As Double
Dim k As Double
Dim tau2 As Double
Sub main()
Dim l As Integer
Dim zeta As Double
Dim u(1 To 4) As Double
Dim x(1 To 4) As Double
Dim z(1 To 4) As Double
Dim e(1 To 4) As Double
Dim a(1 To 4, 1 To 4) As Double
Dim b(1 To 4) As Double
Dim alpha(1 To 4) As Double
Dim m As Integer, i As Integer, j As Integer
Dim max As Double
376
5.6. Modeling of the piano mechanism linking a key with hammer
377
Chapter 5. Quadratic and Linear Splines
max = 0
For m = 1 To 4
If Abs(z(m)) > max Then _
max = Abs(z(m))
Next m
10: If max < zeta Then Exit For
Next j
For m = 1 To 4
11: u(m) = x(m)
Next m
Selection.Cells(i, 1) = (i - 10) * tau
Selection.Cells(i, 2) = u(1)
Selection.Cells(i, 3) = u(2)
Selection.Cells(i, 4) = u(3)
Selection.Cells(i, 5) = (i - 10) * tau
Selection.Cells(i, 6) = u(4)
Selection.Cells(i, 7) = j
Next i
sb = Selection.Cells(10, 1).Address
se = Selection.Cells(10 + l, 2).Address
12: Call graph(sb, se, "t, s", "u1, m")
sb = Selection.Cells(10, 5).Address
se = Selection.Cells(10 + l, 6).Address
13: Call graph(sb, se, "t, s", "u4, m/s")
Range("O36").Select
End Sub
378
5.6. Modeling of the piano mechanism linking a key with hammer
fx(2, 1) = tau2 * k / m1
fx(2, 2) = 1
fx(2, 3) = -tau2 * k / m1
fx(2, 4) = 0
fx(3, 1) = 0: fx(3, 2) = 0
fx(3, 3) = 1
fx(3, 4) = -tau2
m3 = p - q * x(3)
fx(4, 1) = -tau2 * k / m3
fx(4, 2) = 0
fx(4, 3) = tau2 * (k * m3 - _
(q * x(4) ^ 2 + k * (x(1) - x(3))) * q) / m3 ^ 2
fx(4, 4) = 1 - tau * q * x(4) / m3
End Sub
379
Chapter 5. Quadratic and Linear Splines
3) by calling the gauss subroutine (operator 8), the system of linear alge-
braic equations (5.20), defined by arrays a and b, is solved;
4) by means of operator 9, the next approximation of the solution at the t
moment is calculated according to formulas (5.21);
5) operator 10 checks if condition (5.22) is satisfied for termination of the
Newton iterations.
When terminating the iterative process (after leaving the j cycle), values u1 ,
u 2 , u 3 , u 4 of the solution at the t moment (which are in the x array) are
assigned to the u array’s elements by means of operator 11. These values
(together with the value of t and the number of the Newton iterations, jmax ) are
put into cells of Excel.
At the end of the main program (after leaving the i cycle), the graphs of
calculated dependences u1 (t ) and u 4 (t ) are constructed automatically by means
of the graph subroutine. Operators 12 and 13 are the calls of this subroutine.
The declarations of e_functions and fx_jacobian are located below
the main program (see Listing 5.4).
The e_functions subroutine calculates values E1 , E 2 , E 3 , E 4 according
to formulas (5.32). The parameters of this subroutine have the following sense:
x is an array of values u1 , u 2 , u 3 , u 4 ;
e is a one-dimensional array intended for the required values.
The fx_jacobian subroutine calculates the Jacobian matrix of functions
f1 , f 2 , f 3 , f 4 according to formulas (5.18) and (5.37). The parameters have
the following sense:
x is an array of arguments x1 , x 2 , x 3 , x 4 ;
fx is a two-dimensional array intended for the required values of the par-
tial derivatives.
The source data for code Listing 5.4 are the values given in table Listing 5.3
considered above. The corresponding Excel table, depicted in Fig. 5.8, must be
selected before the code execution.
Upon termination of the execution, the values of t, u1 , u 2 , u 3 , u 4 and jmax
are located in the corresponding columns on the Excel worksheet (Fig. 5.9).
Besides, the u1 (t ) and u 4 (t ) graphs are located on this worksheet; Fig. 5.10
shows them completely.
The graphs, depicted in Fig. 5.10, are results of the mentioned calls of the
graph subroutine.
380
5.6. Modeling of the piano mechanism linking a key with hammer
381
Chapter 5. Quadratic and Linear Splines
382
5.7. Definition of linear spline
383
Chapter 5. Quadratic and Linear Splines
The definition of linear spline leads to the following expression for the L(x)
function on elementary segment [ xi 1
, xi ] :
xi x x xi 1
L( x) fi 1
fi , (5.38)
hi hi
where hi xi xi 1
is the elementary segment’s length or the grid step, k + 1 ≤
i ≤ r. Thus, the linear spline is the linearly interpolated tabular function.
Formula (5.38) was already used in programs Listing 4.11 and Listing 4.13:
see formula (4.34) on p. 320.
The error of interpolating the f (x) function (and its derivative) by the L(x)
spline (and by its derivative) is determined by the following expression:
f ( n ) ( x) L( n) ( x) 2 n
O(hmax ), (5.39)
where hmax max {hi } is the maximum grid step ( hmax 0 ), n = 0, 1 is
k 1 i r
384
5.7. Definition of linear spline
b b b r fi fi
1 2
f ( x) dx L( x) dx f ( x) dx hi O( hmax ),
a a a i k 1
2
where hmax 0 is the maximum grid step.
The linear spline can be used in the noniterative method for solving the non-
linear algebraic equation (instead of the cubic spline, Section 4.6). This leads to
a simplification of the program, but also to a deterioration in accuracy of the
equation solution.
We advise the reader to write a program for calculating the values of func-
tion
1
x
u ( x) 1 f ( y ) dy (5.41)
a
385
Chapter 5. Quadratic and Linear Splines
The linear spline can be used in the least-squares method. We will consider
this question on an example of the following table from Task 8.1 in book [13].
The above table gives the values characterizing the land quality and wheat
productivity for each of ν = 12 land plots. The least-squares method allows us to
establish the functional dependence of the wheat productivity, u, on the land
quality mark, x.
Let F (x) be an unknown functional dependence (of a given type) defined up
to parameters c1 , c 2 , ..., c n . More precisely, this dependence looks like
F (c1 , c2 , ..., cn , x ) , where c1 , c 2 , ..., c n and x are the function parameters and
argument, respectively.
According to the least-squares method under consideration, F (x) is the
required functional dependence of productivity u on mark x if the parameters
of F (x) are equal to the coordinates of the minimum point of function
386
5.8. The least-squares method
on c1 , c 2 , ..., c n .
Let us assume that:
1) F (x) is linear spline L(x) at a grid on the x axis;
2) the n number of the grid nodes and their location are given: z1 < ... <
z < ... < z n are the coordinates of the grid nodes on the x axis;
3) parameters c1 , c 2 , ..., c n of F (x) are values L1 , ..., L , ..., Ln of
the L(x) spline at grid nodes z1 , ..., z , ..., z n , respectively.
According to the least-squares method, we have to find the minimum point of
function
on L1 , ..., L , ..., Ln .
In Section 6.12, we will minimize this function iteratively (by subroutines
mini and minim). Here, we will consider a noniterative method to find the
required minimum point, which is based on the concept of fundamental spline.
According to the necessary condition for an extreme value [3], the minimum
points of function (5.43) belong to the set of points that are solutions of the sys-
tem of equations
G
0,
L1
. . .
G
0, (5.44)
Li
. . .
G
0.
Ln
Therefore, for finding the minimum point of function (5.43), we have to solve
the last system and then to analyse the solution results.
The solution of system (5.44) begins with the following concept of funda-
mental spline.
387
Chapter 5. Quadratic and Linear Splines
{ i ( x j )[ L( x j ) u j ]}
j 1
{ i ( x j )[ L1 1 ( x j ) ... L ( x j ) ... Ln n
( x j ) u j ]}
j 1
L1 [ i ( x j ) 1 ( x j )] ... L [ i (x j ) ( x j )] ...
j 1 j 1
Ln [ i (x j ) n
( x j )] [ i ( x j )u j ]
j 1 j 1
L1 ( ij 1 j
) ... L ( ij j
) ... Ln ( ij nj
)
j 1 j 1 j 1
( ij
uj), (5.45)
j 1
where
ij i
(x j ) , (5.46)
1 ≤ i ≤ n, 1 ≤ j ≤ ν,
i.e., coefficients ij
form the A matrix of size n × ν:
388
5.8. The least-squares method
11 12
... 1
21 22
... 2
A . (5.47)
. . . .
n1 n2
... n
qi ( ij j
) , ri ( ij
u j ). (5.49)
j 1 j 1
The system of linear algebraic equations (5.48) can be written as matrix
equation
QL R , (5.50)
where Q is the system matrix, R is the vector of the right-hand sides, L is the
vector of the unknown variables:
The system of linear algebraic equations (5.48) can be solved for unknown
L1 , ..., L , ..., Ln (the linear spline values at the grid nodes) by the Gaussian
elimination method, i.e., by means of subroutine gaus or gauss.
389
Chapter 5. Quadratic and Linear Splines
390
5.9. Program to determine the dependence of the wheat productivity on the land quality
391
Chapter 5. Quadratic and Linear Splines
A(i, j))
Next j
Next i
'Forming matrix Q and vector R:
For i = 1 To n
For k = 1 To n
Q(i, k) = 0
For j = 3 To m
Q(i, k) = Q(i, k) + A(i, j) * A(k, j)
Next j
Next k
R(i) = 0
For j = 3 To m
R(i) = R(i) + A(i, j) * U(j)
Next j
Next i
'Solving system of linear algebraic equations:
2: Call gauss(n, Q, R, L)
'Outputting results:
Selection.Cells(2, 4) = "L"
For i = 1 To n
Selection.Cells(2 + i, 4) = L(i)
Next i
End Sub
392
5.9. Program to determine the dependence of the wheat productivity on the land quality
393
Chapter 5. Quadratic and Linear Splines
394
5.10. The forward and backward Fourier transforms of a periodic function
The Fourier coefficients, amplitude and initial phase are related by the following
formulas:
395
Chapter 5. Quadratic and Linear Splines
ak Ak sin k
,
bk Ak cos k
, (5.57)
Ak ak2 bk2 ,
where k = 1, 2, 3, ...
The calculation of the coefficients of the function’s expansion into the Fouri-
er series is called the analysis or forward Fourier transform. The analysis is de-
fined by formulas (5.53) and (5.54).
The calculation of the f (t ) function’s values, which correspond to the
known coefficients, a 0 , a k and bk (k = 1, 2, 3, ...), is called the synthesis or
backward Fourier transform. The synthesis is defined by formula (5.52).
Along with the Fourier transform theory, which considers the f (t ) function
known at all points of period [0, T ] , there is a theory, which considers the f (t )
function known only at the nodes of a uniform grid on [0, T ] .
Let n be a given number of equal steps or elementary segments [t j 1
, tj],
j = 1, 2, …, n, on period [0, T ] and f (t ) be a grid function given at points
t0 0 , t1 T / n , t2 2T / n , ..., t n 1
( n 1)T / n , t n T . We respectively
denote the f (t ) function’s values at these points as f 0 , f1 , f 2 , ..., f n 1
, fn ,
at that, f 0 = f n because of the f (t ) periodicity. The calculation of the Fourier
coefficients of grid function f (t ) is called the forward discrete Fourier trans-
form. The calculation of values f 0 , f1 , f 2 , ..., f n 1
, f n , which correspond to
the Fourier coefficients, is called the backward discrete Fourier transform.
The Data Analysis add-in for Excel includes the Fourier Analysis procedure
for performing the discrete Fourier transform. We will consider the use of this
procedure on an example of function
f (t ) 1 sin( t ) cos(2 t ) . (5.58)
Into cells A1:A8 on an Excel worksheet, we put this function’s values at the
first n = 8 points (ωt = 0, π/4, π/2, 3π/4, π, 5π/4, 3π/2, 7π/4) of the period with 9
equidistant points (0, π/4, π/2, 3π/4, π, 5π/4, 3π/2, 7π/4, 2π), i.e., we enter num-
bers 2, 1.707107, 1, 1.707107, 2, 0.292893, -1, 0.292893 (Fig. 5.15).
Let us fulfill the following operations:
1) Data > Data Analysis > Fourier Analysis > OK;
2) in the Fourier Analysis window opened, enter $A$1:$A$8 into text box
Input Range;
3) after activating text box Output Range, enter $B$1 into it (Fig. 5.16);
396
5.10. The forward and backward Fourier transforms of a periodic function
4) click on the OK button to get the procedure execution results (Fig. 5.17).
Fig. 5.15. The Excel worksheet with the Fourier analysis source data
Fig. 5.16. The Fourier Analysis window before the procedure execution
Fig. 5.17. The Excel worksheet with the Fourier analysis results
397
Chapter 5. Quadratic and Linear Splines
If we locate the mouse pointer on an exclamation mark (near the B1 cell), the
following information appears: The number in this cell is formatted as text or
preceded by an apostrophe. We should not be afraid of this information.
According to Fig. 5.17, the calculation results (in cells B1:B8) are the coeffi-
cients of the Fourier series in complex form: letter “i” (in cells B2, B4, B6 and
B8) means the imaginary unit, i 1.
The complex representation of the Fourier series [3] can be written as
ik t ik t
f (t ) c0 ck e c k
e ,
k 1
where c0 a0 , c k and c k
are complex Fourier coefficients, k = 1, 2, 3, ...
For using the procedure execution results, we have to know the following:
ik t
1) the values of coefficients c 0 and c k in front of e (k = 1, 2, 3, 4), mul-
tiplied by n = 8, are respectively located in cells B1, B2, B3, B4, B5 (the first half
of the set of complex Fourier coefficients);
ik t
2) the values of coefficients c in front of e k
(k = 1, 2, 3, 4), multi-
plied by 8, are respectively located in cells B8, B7, B6, B5 (the second half of
the set of complex Fourier coefficients);
3) c k = c k = 0 for k > 4.
For verifying it, we will use the following expressions, which follow from the
Euler relation for complex numbers [3]:
ik t ik t ik t ik t
e e ie ie
sin( k t ) , (5.59)
2i 2
ik t ik t
e e
cos( k t ) . (5.60)
2
Using (5.59) at k = 1 and (5.60) at k = 2, we write expression (5.58) in form
i i t 1 i2 t 1 i2 t i i t
f (t ) 1 e e e e . (5.61)
2 2 2 2
Multiplying values c 0 = 1, c1 = i / 2 , c 2 = 1 / 2 , c3 = 0, c 4 = c 4 = 0,
c 3
= 0, c 2
= 1/ 2 , c 1
= i / 2 by 8, we obtain the Fourier analysis results
depicted in Fig. 5.17. Let us pay attention to the following: the value of both 8c4
and 8c 4
is in the B5 cell.
398
5.10. The forward and backward Fourier transforms of a periodic function
ik t ik t
We see that the complex coefficients in front of functions e and e
in expression (5.61) are conjugate, i.e., differ from each other only in the sign in
front of the imaginary unit. This is the property of the expansion of real-valued
ik t
functions, as f (t ) , in terms of e . The expansion of complex-valued func-
ik t
tions in terms of e does not have such property.
In the bottom left corner of the Fourier Analysis window (Fig. 5.16), we see
a little square field (element CheckBox) called Inverse. When clicking on this
field, the check mark appears in it, meaning the switching from the forward
transform (analysis) to the backward transform (synthesis).
Let the worksheet, depicted in Fig. 5.17, be active. To verify the correctness
of working the Fourier Analysis procedure, we fulfill the following operations:
1) Data > Data Analysis > Fourier Analysis > OK;
2) in the Fourier Analysis window opened, enter $B$1:$B$8 into text box
Input Range;
3) after activating text box Output Range, enter $E$1 into it;
4) by clicking on element Inverse, set the check mark in it;
5) click on the OK button for starting the procedure execution.
The execution results are depicted in Fig. 5.18. We see practical coincidence
of columns A and E, and that is natural because the forward and backward Fou-
rier transforms are performed successively.
If the mouse pointer is located on an exclamation mark (near the E1 cell), the
same information appears as in the case of Fig. 5.17.
Fig. 5.18. The Excel worksheet with results of the analysis and synthesis
The main drawback of the Fourier Analysis procedure consists in the follow-
ing: the number of steps on the period is not arbitrary, it must be a power of 2,
i.e., n must be equal to 2, 4, 8 (as in the above example), 16, 32, 64 or so on.
It is because this procedure realizes the so-called fast Fourier transformation [3].
399
Chapter 5. Quadratic and Linear Splines
In this section, we will develop subroutines for the forward and backward
discrete Fourier transforms, free of the drawback formulated at the end of the
previous section. These subroutines will be used in the next section.
At first, let us obtain a discrete analog of formula (5.53) at k = 0, 1, 2, 3, ...
We use designation
f (t ) cos(k t ) g (t ) (5.62)
and consider periodic third-degree spline S (t ) , which respectively assumes
values g 0 , g 1 , g 2 , ..., g n 1
, g n at points 0, t1 , t 2 , ..., t n 1
, tn ( g 0 g n ).
According to expression (4.20), the integral of S (t ) equals
T n gj 1
gj n Mj 1
Mj
S (t ) dt h h3 , (5.63)
0 j 1
2 j 1
24
where h T / n is the grid step, M 0 , M 1 , M 2 , ..., M n 1
, M n are the spline
moments, M 0 Mn.
Let us consider equation (4.9) in form
j
M j 1 2M j j
Mj 1 j
, (5.64)
j = 1, 2, …, n, taking into account the periodicity of g (t ) and S (t ) , i.e., the fol-
lowing equalities:
g n 1 g1 , M n 1 M 1 ,
where g n 1
and M n 1
are the values of the g (t ) and S (t ) functions, respec-
tively, at additional node t n 1
T h . Because of the grid step constancy and
expressions (4.10), we have
1
j j
,
2
3
j
(g j 1
2g j gj 1
).
h2
400
5.11. Subroutines for the forward and backward discrete Fourier transforms
3 n n n
gj 1
2 gj gj 1
h2 j 1 j 1 j 1
or
1 n n 1 n n n n
3
Mj 2 Mj Mj gj 2 gj gj
2 j 1 j 1
2 j 1 h2 j 1 j 1 j 1
or
n
Mj 0.
j 1
Expression (5.63) becomes simpler:
T n gj 1
gj n
S (t ) dt h h gj .
0 j 1
2 j 1
Taking into account expression (5.62), we obtain
2T
ak f (t ) cos( k t ) dt
T 0
2 n 2 n 2
h f j cos(k jh ) f j cos k j . (5.65)
T j 1
n j 1
n
401
Chapter 5. Quadratic and Linear Splines
(n 1) / 2 2 2
fj d0 d 2k 1
sin k j d 2 k cos k j , (5.67)
k 1
n n
1 n
d0 fj , (5.68)
n j 1
2 n 2
d 2k 1
f j sin k j , (5.69)
n j 1
n
2 n 2
d2k f j cos k j , (5.70)
n j 1
n
1 n
dn f j cos( j ) . (5.73)
n j 1
402
5.11. Subroutines for the forward and backward discrete Fourier transforms
403
Chapter 5. Quadratic and Linear Splines
The subroutine name (fouf) occurs from words “Fourier” and “forward”.
The subroutine parameters have the following sense:
n is the number of equal steps on the period;
F is an array of the function values;
D is an array intended for the Fourier coefficients;
m is the doubled number of harmonic oscillations, which are of interest
(this optional parameter is used for possible reducing the execution time).
The basis of this subroutine are formulas (5.68) — (5.70), (5.72) and (5.73).
According to formulas (5.69) and (5.70), the forward discrete Fourier transform
requires the calculation of the sine and cosine values, repeated many times.
These values can be calculated in one of two ways:
by the multiple calls of built-in functions Sin(x) and Cos(x);
by the single call of functions Sin(x) and Cos(x) for calculating the
values of sin( 2 / n) and cos(2 / n) , and by subsequent usage of trigonometric
formulas for calculating the values of sin( kj 2 / n) and cos(kj 2 / n) at k > 1
and/or j > 1.
To reduce the execution time, the second way is used, which is based on the
following trigonometric formulas [3]:
sin( ) sin( ) cos( ) cos( ) sin( ) , (5.74)
cos( ) cos( ) cos( ) sin( ) sin( ) , (5.75)
where α and β are angles.
Into Module15 of the BookNM workbook, we enter the following declaration
of the subroutine for the backward discrete Fourier transform:
Listing 5.8
Sub foub(ByVal n, ByRef F() As Double, _
ByRef D() As Double, Optional m)
Dim m2 As Integer, j As Integer, k2 As Integer
Dim w As Double, z As Double
Dim c0 As Double, s0 As Double
Dim c1 As Double, s1 As Double
Dim c2 As Double, s2 As Double
Const pi As Double = 3.141592654
If IsMissing(m) Then
m2 = n
ElseIf m < 0 Or m > n Then
m2 = n
Else
m2 = m
End If
404
5.11. Subroutines for the forward and backward discrete Fourier transforms
w = 2 * pi / n
c0 = Cos(w): c1 = c0: c2 = c1
s0 = Sin(w): s1 = s0: s2 = s1
For j = 1 To n
z = D(0)
For k2 = 2 To m2 Step 2
z = z + D(k2 - 1) * s2 + D(k2) * c2
w = c2 * c1 - s2 * s1
s2 = s2 * c1 + c2 * s1: c2 = w
Next k2
F(j) = z: w = c1 * c0 - s1 * s0
s1 = s1 * c0 + c1 * s0: s2 = s1
c1 = w: c2 = c1
Next j
F(0) = F(n)
End Sub
The subroutine name (foub) occurs from words “Fourier” and “backward”.
The parameters have the following sense:
n is the number of equal steps on the period;
F is an array intended for the function values;
D is an array of the Fourier coefficients;
m is the doubled number of harmonic oscillations, which are considered.
Formulas (5.67), (5.71), (5.74) and (5.75) are used in the foub subroutine.
405
Chapter 5. Quadratic and Linear Splines
The sound waves, emitted by a sound source (by a vibrating body), propagate
in the medium (in a solid body, liquid or gas) in the form of longitudinal oscilla-
tions of the density of the medium. The ear of an adult person perceives sound
oscillations with frequency 1 / T from 17 — 20 Hz to about 20 kHz.
To lower the sound level (i.e., the amplitude of the density oscillation),
soundproof coverings are used. A technique of constructing such coverings with
given acoustic parameters was developed at the Andreyev Acoustics Institute,
Moscow. According to Fig. 5.19 (from page http://www.akin.ru/r_comm15.htm
of the institute website), the covering is characterized by efficiency with respect
to lowering the sound level. As we see, both the calculated and experimental
dependences for the covering’s efficiency are linear splines whose argument is
the logarithm of frequency k / T k / 2 of harmonic oscillation (5.55).
406
5.12. Solving the sound insulation problem
Let us return to modeling of the bar oscillation in Section 3.20. We will at-
tach weightless membrane Ms (whose area equals A) to the bar and consider that
this membrane is the sound source, at that, dependence u (t ) in Fig. 3.18 is the
Ms membrane deviation. Besides, we will place the mechanism in a box with the
soundproof covering whose efficiency is defined by the calculated (dark) de-
pendence in Fig. 5.19.
We have to answer the following question: by how many decibels is the
sound (from the Ms membrane) attenuated, when it goes through the box’s
soundproof covering?
Outside the box, we place weightless membrane Mr (whose area equals A) of
the sound receiver; u r (t ) is the periodic dependence, which characterizes the Mr
membrane deviation (Fig. 5.20). We have to determine difference Δ (in decibels)
between the intensities of the oscillations of membranes Ms and Mr.
where d 2sk 1
, d 2sk and d 2r k 1
, d 2r k are the Fourier coefficients of dependences
u (t ) and u r (t ) , respectively, k = 1, 2, 3, ...
407
Chapter 5. Quadratic and Linear Splines
408
5.12. Solving the sound insulation problem
d 3r , d 4r , ..., d 23
r r
, d 24 calculated according to formulas (5.80) and (5.81).
As the source data for a program, intended for solving our problem, we use
table Listing 5.9, which includes:
the results of solving the oscillation equation (Fig. 3.18);
the dependence of the covering’s efficiency on the frequency.
Listing 5.9
M 0.001 N 8
K 800 frequency efficiency
L 100 17 5
F t u 45 1
0.00E+00 0.00E+00 6.62E-04 100 13.8
0.00E+00 2.00E-03 -5.89E-03 126 10
0.00E+00 4.00E-03 5.89E-03 158 8.8
0.00E+00 6.00E-03 -1.60E-03 720 8.8
0.00E+00 8.00E-03 -3.07E-03 1100 10
0.00E+00 1.00E-02 4.66E-03 1600 10
0.00E+00 1.20E-02 -2.57E-03
0.00E+00 1.40E-02 -1.01E-03
0.00E+00 1.60E-02 3.20E-03
0.00E+00 1.80E-02 -2.67E-03
0.00E+00 2.00E-02 2.91E-04
0.00E+00 2.20E-02 1.87E-03
0.00E+00 2.40E-02 -2.27E-03
0.00E+00 2.60E-02 9.54E-04
5.00E+00 2.80E-02 8.20E-04
1.00E+01 3.00E-02 1.65E-02
5.00E+00 3.20E-02 1.77E-02
0.00E+00 3.40E-02 -1.46E-02
0.00E+00 3.60E-02 1.48E-03
0.00E+00 3.80E-02 1.03E-02
0.00E+00 4.00E-02 -1.25E-02
0.00E+00 4.20E-02 5.17E-03
0.00E+00 4.40E-02 4.59E-03
0.00E+00 4.60E-02 -9.23E-03
0.00E+00 4.80E-02 6.32E-03
0.00E+00 5.00E-02 6.62E-04
409
Chapter 5. Quadratic and Linear Splines
The subtable with the dependence of the covering’s efficiency on the fre-
quency includes:
N, the number of the frequency values;
the frequency values (in hertzs) in column frequency;
the efficiency values (in decibels) in column efficiency, according to the
dark dependence in Fig. 5.19.
The program follows:
Listing 5.10
Sub main()
Dim T() As Double
Dim U() As Double
Dim D() As Double
Dim m As Integer
Dim N As Integer
Dim j As Integer, k2 As Integer
Dim i As Integer
Dim sb As String, se As String
Dim fr As Double, eff As Double
Dim ln_frequ() As Double
Dim efficiency() As Double
Dim MOM() As Double
Dim Ps As Double, Pr As Double
Dim w As Double
m = Selection.Rows.Count 'quantity of rows
N = Selection.Cells(1, 5)
ReDim T(0 To m - 5)
ReDim U(0 To m - 5)
ReDim D(0 To m - 5)
ReDim ln_frequ(1 To N)
ReDim efficiency(1 To N)
ReDim MOM(1 To N)
For j = 0 To m - 5
T(j) = Selection.Cells(j + 5, 2)
U(j) = Selection.Cells(j + 5, 3)
Next j
sb = Selection.Cells(5, 2).Address
se = Selection.Cells(m, 3).Address
0: Call graph(sb, se, "t, s", "u, m")
For i = 1 To N
ln_frequ(i) = Log(Selection.Cells(i + 2, 4))
efficiency(i) = Selection.Cells(i + 2, 5)
410
5.12. Solving the sound insulation problem
MOM(i) = 0
Next i
1: Call fouf(m - 5, U, D)
D(0) = 0
fr = 1 / T(m - 5) 'value of main frequency 1/T
'Calculating value of Ps:
w = 0
For k2 = 2 To m - 5 Step 2
w = w + D(k2 - 1) ^ 2 + D(k2) ^ 2
Next k2
Ps = 10 * Log(w) / 2.302585093
'Calculating value of Pr:
w = 0
For k2 = 2 To m - 5 Step 2
2: Call si(1, N, ln_frequ, efficiency, MOM, _
Log(k2 / 2 * fr), eff)
D(k2 - 1) = D(k2 - 1) * 10 ^ (-eff / 20)
D(k2) = D(k2) * 10 ^ (-eff / 20)
w = w + D(k2 - 1) ^ 2 + D(k2) ^ 2
Next k2
Pr = 10 * Log(w) / 2.302585093
'Calculating sound attenuation:
3: w = Ps - Pr
4: MsgBox "delta =" & Str(Round(w, 3)) & " dB"
'Synthesis of time dependence:
5: Call foub(m - 5, U, D)
sb = Selection.Cells(5, 6).Address
se = Selection.Cells(m, 7).Address
Selection.Cells(4, 6) = "t"
Selection.Cells(4, 7) = "ur"
For j = 0 To m - 5
Selection.Cells(j + 5, 6) = T(j)
Selection.Cells(j + 5, 7) = U(j)
Next j
6: Call graph(sb, se, "t, s", "ur, m")
Range("O33").Select
End Sub
Operator 0 of this program creates the u (t ) graph of the bar deviation, i.e.,
of the deviation of membrane Ms, which is the sound source. For that, the
graph subroutine (Section 4.8) is used for the first time.
411
Chapter 5. Quadratic and Linear Splines
412
5.12. Solving the sound insulation problem
2) the window with the Δ value of the sound attenuation appears (Fig. 5.22);
3) after clicking on OK, the u r (t ) dependence and its graph appear.
Fig. 5.23 shows the Excel worksheet upon termination of the program execu-
tion. The automatically constructed graphs of dependences u (t ) and u r (t ) are
on this worksheet; Fig. 5.24 shows them completely.
413
Chapter 5. Quadratic and Linear Splines
We advise the reader to return to the task on p. 279 for calculating the Fouri-
er coefficients of dependences v(t ) and i (t ) .
414
Chapter 6.
Numerical Methods
for Nonlinear Programming
415
Chapter 6. Numerical Methods for Nonlinear Programming
416
6.1. Minimizing linear and nonlinear functions of several variables by the Solver add-in
We used the Solver add-in for solving the nonlinear algebraic equation (Sec-
tion 4.5). Let us consider two more examples of using this add-in — for solving
problems of linear and nonlinear programming.
Initially, we will solve the following transportation problem of linear pro-
gramming from article [15].
There are three points (A1, A2, A3 ) for sending identical loads and four points
( B1, B2, B3, B4 ) for receiving them. Let cij be the expenses for relocation of one
load from Ai to Bj (i = 1, 2, 3, j = 1, 2, 3, 4). We have to find the minimum of
total expenses for the required relocations from points A1, A2, A3 to points B1,
B2, B3, B4.
More precisely, the source data for the problem include:
the matrix of expenses for transportation of one load looking like
c11 c12 c13 c14 3 4 5 6
C c21 c22 c23 c24 4 4 2 1 ;
c31 c32 c33 c34 2 1 6 8
the number of loads at points A1, A2, A3: a1 8 , a2 5 , a3 7;
the requirement for loads at points B1, B2, B3, B4: b1 4 , b2 4,
b3 2 , b4 10 (note that b1 b2 b3 b4 a1 a2 a3 ).
We have to find:
the minimum of total expenses for the load relocations from points A1,
A2, A3 to points B1, B2, B3, B4;
the corresponding number of loads relocated from point Ai to point Bj
(i = 1, 2, 3, j = 1, 2, 3, 4).
For solving the formulated problem, let us put:
the C matrix into range A1:D3 on an Excel worksheet;
values a1 8 , a2 5 , a3 7 into cells E1:E3 of the same worksheet;
values b1 4 , b2 4 , b3 2 , b4 10 into cells A4:D4 (Fig. 6.1).
417
Chapter 6. Numerical Methods for Nonlinear Programming
=SUMPRODUCT(A1:D3;A5:D7)
418
6.1. Minimizing linear and nonlinear functions of several variables by the Solver add-in
corresponding to mathematical formula (6.2). Into cells E5, E6 and E7, we enter
formulas
=SUM(A5:D5)
=SUM(A6:D6)
=SUM(A7:D7)
corresponding to the left-hand side of constraints (6.3). Into cells A8, B8, C8 and
D8, we enter formulas
=SUM(A5:A7)
=SUM(B5:B7)
=SUM(C5:C7)
=SUM(D5:D7)
Fig. 6.2. The Excel worksheet with the formulas in the cells: the shaded
top and bottom ranges correspond to the C and X matrices, respectively
419
Chapter 6. Numerical Methods for Nonlinear Programming
6) enter Simplex LP into box Select a Solving Method by means of the drop-
down list (Fig. 6.3);
7) click on the Solve button;
8) in the Solver Results window opened, click on OK.
Results of minimizing function (6.2) with constraints (6.3) and (6.4) appear
in cell F2 and range A5:D7 (Fig. 6.4).
Value 58 in cell F2 gives the minimum of total expenses for the load reloca-
tions. The contents of range A5:D7 suggest the distribution of the load reloca-
tions for minimizing the total expenses.
For example:
420
6.1. Minimizing linear and nonlinear functions of several variables by the Solver add-in
value x11 1 (in cell A5) means that one load must be relocated from
point A1 to point B1;
value x24 5 (in cell D6) means that five loads must be relocated from
point A2 to point B4.
According to the source data for the problem solved by us, equality
3 4
ai bj
i 1 j 1
is satisfied. If this equality is not satisfied, that is,
3 4
ai bj ,
i 1 j 1
we should introduce virtual point B5 (for receiving the loads) and consider that
3 4
b5 ai bj ,
i 1 j 1
Further, we use the above method for solving the problem of minimizing the
total expenses for the load relocations from points A1, A2, A3 to points B1, B2,
B3, B4, B5. The calculated values of x15 , x25 , x35 are the numbers of loads
remaining at points A1, A2, A3.
421
Chapter 6. Numerical Methods for Nonlinear Programming
According to the fourth chapter of book [2], the considered operation mode
of Solver for Excel 2007 can be used for solving the system of linear algebraic
equations (3.49). Solver for the later versions of Excel does not have this ability.
Below, we will minimize nonlinear function (6.1), the Rosenbrock function,
by means of the Solver add-in. The graph of this rather popular test function is
depicted in Fig. 6.5, which is taken from the following page of Wikipedia, the
free encyclopedia: http://en.wikipedia.org/wiki/Rosenbrock_function.
The following is obvious:
nonlinear function (6.1) is continuous and non-negative;
point x of the function minimum has coordinates x1 x2 1 , and
F (1, 1) 0;
point x is in “ravine” (on the dark stripe in Fig. 6.5).
Let us show that the Rosenbrock function does not have other minimum points.
The partial derivatives of function (6.1) are defined by the following algebra-
ic expressions:
422
6.1. Minimizing linear and nonlinear functions of several variables by the Solver add-in
x2 x12 0.
According to the second equation, x2 x12 . Substituting this expression into the
=100*(H1-G1^2)^2+(1-G1)^2
423
Chapter 6. Numerical Methods for Nonlinear Programming
Fig. 6.7. The Solver Parameters window before minimizing function (6.1)
424
6.1. Minimizing linear and nonlinear functions of several variables by the Solver add-in
The Excel formula, intended for calculating the values of objective function
F ( x1 , x 2 ) , may include Excel functions, in particular, user-defined functions.
To demonstrate this, let us consider the following user-defined function corre-
sponding to mathematical function (6.1).
Listing 6.1
Function Rosenbrock(x1, x2)
Rosenbrock = 100 * (x2 - x1 ^ 2) ^ 2 + _
(1 - x1) ^ 2
End Function
We put this declaration into Module16 of the BookNM workbook and formula
=Rosenbrock(G1;H1)
425
Chapter 6. Numerical Methods for Nonlinear Programming
Fig. 6.10. The Options window with option Show Iteration Results turned on
426
6.1. Minimizing linear and nonlinear functions of several variables by the Solver add-in
Fig. 6.11a shows the result of the first iteration. After the next 4 clicks on
Continue in window Show Trial Solution, we see the result of the 5th iteration
(Fig. 6.11b). After the next 16 clicks on Continue, the Solver Results window
appears. We click on OK in the last window to terminate the execution.
Fig. 6.12, which is similar to Fig. 6.8, shows the result. Thus, 21 iterations were
performed.
The Powell minimization method (Section 6.5) gives the same result after 5
iterations (p. 454).
Fig. 6.11. The worksheet after the 1st (a) and 5th (b) iterations
427
Chapter 6. Numerical Methods for Nonlinear Programming
428
6.2. Method for minimizing a nonlinear function of one variable
429
Chapter 6. Numerical Methods for Nonlinear Programming
2. Of the four points (a, b, c, d ), three neighboring points are chosen, such
that the function value at the midpoint is less than the function values at the
endpoints. These three points are denoted by letters a, b, c; the corresponding
function values are denoted by f a , f b , f c , respectively. As a result, the uncer-
tainty segment, [a, c] , is reduced to one and a half times (Fig. 6.15).
3. The minimum point of the parabola, passing through points A = (a, f a ),
B = (b, f b ), C = (c, f c ), is calculated according to formula
f a (b 2 c2 ) fb (c 2 a2 ) fc ( a 2 b2 )
d 0.5 . (6.7)
f a (b c) fb (c a) fc ( a b)
The derivation of this formula is given below.
4. Value f d f (d ) is calculated (Fig. 6.15). The jump to the first item is
performed.
Fig. 6.15. The results of reducing the uncertainty segment to 1.5 times and
of the parabolic interpolation: [a, c] is the resulting uncertainty segment;
b is the midpoint of [a, c] ; d is the minimum point of the parabola
430
6.2. Method for minimizing a nonlinear function of one variable
431
Chapter 6. Numerical Methods for Nonlinear Programming
432
6.3. The coordinate-descent method
If d <> 0 Then
MsgBox "mini: Array ss is non-diagonal"
End 'immediate termination of macro
End If
For j = 1 To n
For i = 1 To n
sss(i, j) = ss(i, j)
Next i
Next j
m1: For i = 0 To n
y(i) = x(i)
z(i) = x(i)
Next i
For j = 1 To n 'j - number of descent direction
For i = 1 To n
s(i) = ss(i, j)
Next i
d = 0
For i = 1 To n
d = s(i) ^ 2 + d
Next i
If d = 0 Then
For i = 1 To n
s(i) = sss(i, j)
Next i
Else
For i = 1 To n
sss(i, j) = s(i)
Next i
End If
'Finding uncertainty segment:
fa = y(0): fb = y(0): fc = y(0)
a = 0: b = 0: c = 0
d = 1: e = 1
s1: For i = 1 To n
x(i) = y(i) + d * s(i)
Next i
Call func(n, x)
If Not IsMissing(alpha) Then
If x(0) < alpha Then GoTo m3
End If
fd = x(0)
433
Chapter 6. Numerical Methods for Nonlinear Programming
If fd < fa Then
fc = fb: fb = fa: fa = fd
c = b: b = a: a = d
d = 2 * d + e
GoTo s1
Else
If fa = fb Then
fb = fd
b = d
e = -2 * d
d = e
GoTo s1
End If
End If
fc = fb: fb = fa: fa = fd
c = b: b = a: a = d
d = (a + b) * 0.5
For i = 1 To n
x(i) = y(i) + d * s(i)
Next i
Call func(n, x)
If Not IsMissing(alpha) Then
If x(0) < alpha Then GoTo m3
End If
fd = x(0)
'Reducing uncertainty segment:
s2: If Abs(fb - fd) < rho * fb Then GoTo s0
If (c - d) * (d - b) < 0 Then
If fd < fb Then
fc = fb: fb = fd
c = b: b = d
Else
fa = fd
a = d
End If
Else
If fd < fb Then
fa = fb: fb = fd
a = b: b = d
Else
fc = fd
c = d
434
6.3. The coordinate-descent method
End If
End If
d = fa * (b - c) + fb * (c - a) + fc * (a - b)
If d = 0 Then GoTo s0
d = (fa * (b * b - c * c) + _
fb * (c * c - a * a) + _
fc * (a * a - b * b)) / (2 * d)
For i = 1 To n
x(i) = y(i) + d * s(i)
Next i
Call func(n, x)
If Not IsMissing(alpha) Then
If x(0) < alpha Then GoTo m3
End If
fd = x(0)
GoTo s2
s0: For i = 1 To n
ss(i, j) = x(i) - y(i)
y(i) = x(i)
Next i
y(0) = x(0)
Next j
'Checking condition of minimization termination:
m3: If Not IsMissing(alpha) Then
If test(n, x, z, rho, alpha) Then GoTo m1
Else
If test(n, x, z, rho) Then GoTo m1
End If
End Sub
The mini subroutine under consideration has five parameters, and parameter
alpha is optional.
The obligatory parameters have the following sense:
n is the number of variables;
x is an array with elements x(0), x(1), x(2), …, x(n), at that,
memory cell x(0) contains the F function’s value corresponding to the values
of x1 , x 2 , …, x n being in memory cells x(1), x(2), …, x(n), respectively;
ss is a two-dimensional array n × n, corresponding to diagonal matrix S
of initial steps: memory cell ss(1, 1) contains the initial step along the
x1 axis, cell ss(2, 2) contains the initial step along the x 2 axis, …, cell
435
Chapter 6. Numerical Methods for Nonlinear Programming
ss(n, n) contains the initial step along the x n axis (the diagonal matrix is
a square matrix that has nonzero elements only on its main diagonal);
rho is the relative change in F, terminating the minimization along an
axis (see in the first item of the algorithm in the previous section).
The above declaration of the mini subroutine, Listing 6.2, contains three
calls of the func subroutine intended for calculation of the F function’s value
(the value of the x(0) element) corresponding to the current values of elements
x(1), x(2), …, x(n).
Optional parameter alpha of the mini subroutine is used when we know
that the minimum value of non-negative function F is equal to zero: when condi-
tion F is satisfied, operator GoTo m3 (following the func subroutine
calls) is performed, and then the test function is called.
In the test function declaration, conditions must be formulated for termi-
nating the minimization. The call of this function is performed when F and
also at the end of every iteration, that is, after minimizations of the F function on
all arguments x1 , x 2 , …, x n .
Function test returns True to the mini subroutine if none of the minimi-
zation termination conditions is satisfied. In this case, the next iteration is per-
formed (that is, the minimizations of the F function on arguments x1 , x 2 , …,
x n are repeated) and the call of function test is again performed. The mini
subroutine execution is terminated when test returns False.
To control the course of the x0 F ( x1 , x2 , ..., xn ) function minimization,
the test function declaration must contain operators for putting the current
values of elements x(0), x(1), x(2), …, x(n) into cells on the Excel work-
sheet.
Note that from iteration to iteration in the course of the minimization:
not only one-dimensional array x is being changed, but two-dimensional
array ss, corresponding to matrix S of initial steps for the next iteration, is also
being changed;
when changing array ss, the S matrix remains diagonal in the considered
coordinate-descent method.
436
6.4. Examples of using the minimization methods
The mini subroutine from the previous section will be used for solving the
following two tasks: the optimization of a tin can and the Rosenbrock function
minimization.
The optimization of a tin can.
According to this task, we have to determine a variant of the cylindrical tin
can of a given volume, which is the best in terms of the amount of tin required.
The volume and total area of a right circular cylinder [3] are respectively
defined by formulas
V r 2h ,
A 2 r ( r h) ,
where r is the base radius, h is the height. The first formula leads to
V
h . (6.8)
r2
By means of this expression, we eliminate h from the second formula:
V
A( r ) 2 r 2 2 . (6.9)
r
For given volume V of the tin can, the total area is defined by the last formu-
la. We have to find the minimum point of the A(r ) function for positive values
of the r argument.
Because the objective function, A(r ) defined by (6.9), has a simple form, the
optimization task can be solved analytically. For that, according to [3], we must
fulfill the following:
1) find real roots of equation
dA
0; (6.10)
dr
2) choose those of the roots, which are positive and satisfy the following
inequality:
437
Chapter 6. Numerical Methods for Nonlinear Programming
d2A
0.
dr 2
Using formula (6.9) and the basic rules of differentiation [3], we obtain
dA 2
(2 r 3 V ) .
dr r 2
Thus, equation (6.10) becomes
2 r3 V 0.
This equation has only one real root:
V
r . 3 (6.11)
2
The second derivative of the A(r ) function equals
d2A 4
( r3 V).
2 3
dr r
We see that the second derivative is positive for any positive value of r. There-
fore, formula (6.11) gives the desired optimal value of r.
According to formula (6.11), for V = 1000 cm3 (that is, in the case of the one-
liter can), the optimal base radius is equal to r = 5.41926 cm. Formulas (6.8)
and (6.9) lead to the following optimal values of the height and total area of the
tin can: h = 10.83853 cm, A = 553.5810 cm2.
For optimizing the one-liter can by means of subroutine mini, we enter the
following text of program main, subroutine func and function test into
Module1 of the BookNM workbook.
Listing 6.3
Dim nf As Long 'counter of calls of func
Dim nt As Long 'counter of calls of test
Sub main()
Dim x() As Double
Dim ss() As Double
Dim n As Byte
n = 1 'number of variables
ReDim x(n)
438
6.4. Examples of using the minimization methods
ReDim ss(1 To n, 1 To n)
x(1) = Range("Sheet2!G1").Value
ss(1, 1) = Range("Sheet2!G2").Value
If ss(1, 1) ^ 2 = 0 Then
Range("Sheet2!A1").Value = _
"Initial step must be increased"
End
End If
nf = 0
nt = 0
0: Call func(n, x) 'it must be before minimization
1: Call mini(n, x, ss, 1E-6)
End Sub
1
, nt and nf are put into the nt-th row on the Sheet2 worksheet.
439
Chapter 6. Numerical Methods for Nonlinear Programming
2 4 V
F( 1
) A( 1
) 2 1
2 . (6.12)
2
1
2
We made substitution r 1
in order to have only non-negative values of the r
radius in the course of the A area minimization. The tin can volume is given in
the func subroutine; it is equal to V = 1000.
The initial approximation of the minimum point, x(1) = 1 , and initial step
ss(1, 1) = s11 are respectively taken from cells G1 and G2 on the Sheet2
worksheet. The sign of s11 determines the direction of the initial step, and | s11 |
determines its size. Before the mini subroutine call (operator 1), the initial
value of objective function x(0) = F ( 1 ) must be defined. For that, operator 0
is used, which calculates the x(0) value corresponding to the x(1) value by
means of the func subroutine.
Fig. 6.16 shows the Sheet2 worksheet (a) before and (b) after the execution
of code Listing 6.3. According to Fig. 6.16a, the initial value of the 1 variable
equals 1, initial step s11 equals 0.01.
440
6.4. Examples of using the minimization methods
According to Fig. 6.16b, only one iteration was performed for the minimiza-
tion of function (6.12) because it is a function of one variable (see operator 3);
the iteration result is in cells A1 and B1. The final value of 1 (which is in the
B1 cell) is equal to 2.328087. In this case, the radius of the tin can base,
2
r 1
= 5.41999, is close to the optimal value, r = 5.41926, calculated
according to formula (6.11). During the search for the minimum point, 13 values
of the objective function were calculated. The final value of the objective
function (which is in the A1 cell) is equal to A = 553.5811.
Fig. 6.16. The Sheet2 worksheet (a) before and (b) after minimization of F ( 1
)
We see conditional operator 2 in code Listing 6.3. It can be replaced with one
of the following two assignment operators with logical expression in the right-
hand side:
or
441
Chapter 6. Numerical Methods for Nonlinear Programming
Sub main()
Dim x() As Double
Dim ss() As Double
Dim n As Byte
Dim i As Byte, j As Byte
Dim d As Double
n = 2 'number of variables
ReDim x(n)
ReDim ss(1 To n, 1 To n)
For j = 1 To n
x(j) = Worksheets("Sheet2").Cells(1, 6 + j)
For i = 1 To n
ss(i, j) = Worksheets("Sheet2"). _
Cells(1 + i, 6 + j)
Next i
Next j
For j = 1 To n
d = 0
For i = 1 To n
d = ss(i, j) ^ 2 + d
Next i
If d = 0 Then
Range("Sheet2!A1").Value = _
"You must increase" & Str(j) & _
"-th initial step"
End
End If
Next j
nf = 0
nt = 0
Call func(n, x) 'it must be before minimization
1: Call mini(n, x, ss, 1E-6, 1E-6)
End Sub
442
6.4. Examples of using the minimization methods
443
Chapter 6. Numerical Methods for Nonlinear Programming
Fig. 6.17 shows worksheet Sheet2 (a) before and (b, c) after executing code
Listing 6.4.
Coordinates x(1) = x1 , x(2) = x 2 of the initial approximation of the
minimum point and also initial steps ss(1, 1) = s11 , ss(2, 2) = s 22 are
respectively taken from ranges G1:H1 and G2:H3 on worksheet Sheet2
(Fig. 6.17a). Before calling the mini subroutine, the initial value of the
objective function is calculated by calling the func subroutine. The result of
the Rosenbrock function minimization is located in range A2066:C2066
(Fig. 6.17c).
444
6.4. Examples of using the minimization methods
According to Fig. 6.17a, the initial values of the variables equal x10 = -5.5,
x 20 = 0.5 (we used these initial values in Section 6.1 when minimizing the
Rosenbrock function by the Solver add-in), initial steps s11 and s 22 are equal to
0.01, and s12 = s 21 = 0.
Fig. 6.17b and 6.17c show the results of the initial and final iterations.
According to Fig. 6.17c, the result of the execution of code Listing 6.4 is
x1 = x 2 = 1, and during the execution:
2066 iterations were performed;
16781 values of objective function (6.1) were calculated.
Further, we will consider the Powell minimization method. According to
Fig. 6.18 (similar to Fig. 6.17c), the method usage reduces:
the number of iterations to 5;
the number of the calculated values of objective function (6.1) to 376.
445
Chapter 6. Numerical Methods for Nonlinear Programming
tions S 1 , S 2 , ..., S n (which are defined by the S matrix), at that, a set of direc-
tions for the next iteration is formed. More precisely, one iteration includes the
following seven stages.
1. For i = 1, 2, …, n, vectors x i are defined according to recurrence formula
xi xi 1
i
Si ,
where x 0 is the initial approximation of the minimum point for the given itera-
tion, i
is the minimum point of the following function of one variable:
fi ( ) F (xi 1
Si ) .
2. The maximum change in the F (x) function,
max {F (xi 1
) F (xi )} ,
1 i n
is defined. Integer k is defined as the serial number of the direction along which
this change has happened.
3. Values Fa F ( 2x n x0 ) , Fb F ( x n ) , Fc F (x0 ) are defined.
4. If Fa Fc 0 and
2
Fc Fb
2( Fc 2 Fb Fa ) ,
Fa Fc
446
6.5. The Powell minimization method
then the 5th item is fulfilled. Otherwise, x n is assigned to x 0 , and the jump to
the 7th item is performed without changing the set of minimization directions.
5. Two vectors are defined according to formulas
Sn 1
xn x0 ,
x xn Sn 1
,
447
Chapter 6. Numerical Methods for Nonlinear Programming
Next j
m1: For i = 0 To n
y(i) = x(i)
z(i) = x(i)
Next i
dm = 0
For j = 1 To n 'j - number of descent direction
For i = 1 To n
s(i) = ss(i, j)
Next i
d = 0
For i = 1 To n
d = s(i) ^ 2 + d
Next i
If d = 0 Then
For i = 1 To n
s(i) = sss(i, j)
Next i
Else
For i = 1 To n
sss(i, j) = s(i)
Next i
End If
'Finding uncertainty segment:
fa = y(0): fb = y(0): fc = y(0)
a = 0: b = 0: c = 0
d = 1: e = 1
s1: For i = 1 To n
x(i) = y(i) + d * s(i)
Next i
Call func(n, x)
If Not IsMissing(alpha) Then
If x(0) < alpha Then GoTo m3
End If
fd = x(0)
If fd < fa Then
fc = fb: fb = fa: fa = fd
c = b: b = a: a = d
d = 2 * d + e
GoTo s1
Else
If fa = fb Then
448
6.5. The Powell minimization method
fb = fd
b = d
e = -2 * d
d = e
GoTo s1
End If
End If
fc = fb: fb = fa: fa = fd
c = b: b = a: a = d
d = (a + b) * 0.5
For i = 1 To n
x(i) = y(i) + d * s(i)
Next i
Call func(n, x)
If Not IsMissing(alpha) Then
If x(0) < alpha Then GoTo m3
End If
fd = x(0)
'Reducing uncertainty segment:
s2: If Abs(fb - fd) < rho * fb Then GoTo s0
If (c - d) * (d - b) < 0 Then
If fd < fb Then
fc = fb: fb = fd
c = b: b = d
Else
fa = fd
a = d
End If
Else
If fd < fb Then
fa = fb: fb = fd
a = b: b = d
Else
fc = fd
c = d
End If
End If
d = fa * (b - c) + fb * (c - a) + fc * (a - b)
If d = 0 Then GoTo s0
d = (fa * (b * b - c * c) + _
fb * (c * c - a * a) + _
fc * (a * a - b * b)) / (2 * d)
449
Chapter 6. Numerical Methods for Nonlinear Programming
For i = 1 To n
x(i) = y(i) + d * s(i)
Next i
Call func(n, x)
If Not IsMissing(alpha) Then
If x(0) < alpha Then GoTo m3
End If
fd = x(0)
GoTo s2
s0: d = y(0) - x(0)
If d > dm Then
dm = d
m = j
End If
For i = 1 To n
ss(i, j) = x(i) - y(i)
y(i) = x(i)
Next i
y(0) = x(0)
Next j
If n = 1 Then GoTo m3
'Last descent:
For i = 1 To n
x(i) = 2 * y(i) - z(i)
Next i
Call func(n, x)
If Not IsMissing(alpha) Then
If x(0) < alpha Then GoTo m3
End If
fa = x(0): fb = y(0): fc = z(0)
a = fa - fc
If a >= 0 Then GoTo m2
a = (fc - fb - dm) / a
If 2 * (fc - 2 * fb + fa) * a ^ 2 >= dm Then _
GoTo m2
For j = m To n - 1
k = j + 1
For i = 1 To n
ss(i, j) = ss(i, k)
Next i
Next j
For i = 1 To n
450
6.5. The Powell minimization method
451
Chapter 6. Numerical Methods for Nonlinear Programming
If fd < fb Then
fc = fb: fb = fd
c = b: b = d
Else
fa = fd
a = d
End If
Else
If fd < fb Then
fa = fb: fb = fd
a = b: b = d
Else
fc = fd
c = d
End If
End If
d = fa * (b - c) + fb * (c - a) + fc * (a - b)
If d = 0 Then GoTo h0
d = (fa * (b * b - c * c) + _
fb * (c * c - a * a) + _
fc * (a * a - b * b)) / (2 * d)
For i = 1 To n
x(i) = y(i) + d * s(i)
Next i
Call func(n, x)
If Not IsMissing(alpha) Then
If x(0) < alpha Then GoTo m3
End If
fd = x(0)
GoTo h2
h0: For i = 1 To n
ss(i, n) = x(i) - y(i)
y(i) = x(i)
Next i
y(0) = x(0)
'Writing result of descents into array x:
m2: For i = 0 To n
x(i) = y(i)
Next i
'Checking condition of minimization termination:
m3: If Not IsMissing(alpha) Then
If test(n, x, z, rho, alpha) Then GoTo m1
452
6.5. The Powell minimization method
Else
If test(n, x, z, rho) Then GoTo m1
End If
End Sub
The minim subroutine parameters have the same sense as the corresponding
parameters of the mini subroutine (p. 435). However, two-dimensional array
ss may be non-diagonal.
In the minim subroutine, elements ss(1, j), ss(2, j), ..., ss(n, j) of
the ss array, corresponding to the j-th column ( S j ) of the S matrix, define the
j-th descent direction and the initial step along this direction, which equals
sj s12j s22 j ... 2
snj , j = 1, 2, ..., n. The descent directions, defined by the
ss array (matrix S ), is generally changing from iteration to iteration during the
F ( x1 , x2 , ..., xn ) function minimization.
Let us test the new subroutine by means of the Rosenbrock function. For this
purpose, we replace line
with line
in Listing 6.4. We leave subroutine func, function test and the initial data
without change.
The result of the Rosenbrock function minimization by the Powell method is
located in cells A5:C5 (Fig. 6.18).
Fig. 6.18. The Sheet2 worksheet upon termination of the code execution
453
Chapter 6. Numerical Methods for Nonlinear Programming
We see that the obtained minimum point is the same as when using the
Solver add-in and coordinate-descent method: x1 = x 2 = 1. The minimization
of function (6.1) requires:
5 iterations of the Powell method (Fig. 6.18);
21 iterations of Solver (p. 427);
2066 iterations of the coordinate-descent method (p. 445).
Thus, the Powell method is more efficient than the Solver add-in and coordi-
nate-descent method for the Rosenbrock function. This is due to the following:
1) minimum point x (1, 1) is located in the ravine (p. 422);
2) in the Powell method, the initial descent directions, which are parallel to
the x1 and x 2 axes, are being converted to the descent directions, S 1 and S 2 ,
oriented along the ravine bottom (Fig. 6.19).
Fig. 6.19. The level curves of the Rosenbrock function in the neighborhood
of the minimum point and vectors S 1 and S 2 for the 4th iteration
454
6.5. The Powell minimization method
The iteration results, ( x11 , x12 ) , ( x12 , x22 ) , ( x13 , x23 ) , ( x14 , x24 ) , …, approach
minimum point x (1, 1) along the ravine bottom. This assertion follows from
Fig. 6.18 and 6.19.
455
Chapter 6. Numerical Methods for Nonlinear Programming
Fig. 6.20. The four-spring system: the x 3 axis is directed “towards us”
and passes through the springs junction point with zero coordinates
The outside force, vector f directed along the x 3 axis (for example, the force
of gravity), acts on body M attached to the springs junction. The value of this
force, f | f | , is given, and this value is negative if vector f and axis x 3 do
not coincide in direction (according to the common practice in physics), i.e., the
vector is directed “from us” (Fig. 6.20). The elastic constants of the springs equal
K 1 , K 2 , K 3 , K 4 , respectively.
456
6.6. Determining the equilibrium state of a four-spring system
Sub main()
Dim x() As Double
Dim ss() As Double
Dim n As Byte, i As Byte, j As Byte
Dim d As Double
K1 = Range("Sheet2!G5").Value
K2 = Range("Sheet2!H5").Value
457
Chapter 6. Numerical Methods for Nonlinear Programming
K3 = Range("Sheet2!I5").Value
K4 = Range("Sheet2!J5").Value
f = Range("Sheet2!G6").Value
C = Range("Sheet2!H6").Value
n = 3 'number of variables
ReDim x(n)
ReDim ss(1 To n, 1 To n)
For j = 1 To n
1: x(j) = Worksheets("Sheet2").Cells(1, 6 + j)
For i = 1 To n
2: ss(i, j) = Worksheets("Sheet2"). _
Cells(1 + i, 6 + j)
Next i
Next j
For j = 1 To n
d = 0
For i = 1 To n
d = ss(i, j) ^ 2 + d
Next i
If d = 0 Then
Range("Sheet2!A1").Value = _
"You must increase" & Str(j) & _
"-th initial step"
End
End If
Next j
nf = 0
nt = 0
Call func(n, x) 'it must be before minimization
3: Call mini(n, x, ss, 1E-6)
End Sub
458
6.6. Determining the equilibrium state of a four-spring system
The test function returns False when the relative change of function
(6.13) on one iteration becomes less than 3ρ = 3·10-6 (the number of arguments is
equal to 3). In this case, the search of the minimum point terminates.
When executing the test function, the values of x(0), x(1), x(2),
x(3), nt and nf are put into cells on the Sheet2 worksheet.
By means of operators 1 and 2, coordinates x(1), x(2), x(3) of the initial
approximation of the minimum point and initial steps ss(1, 1), ss(2, 2),
ss(3, 3) are respectively taken from ranges G1:I1 and G2:I4 on the Sheet2
worksheet. Assignment operators 1 and 2 interpret the contents of the empty
cells as zero.
Elastic constants K 1 , K 2 , K 3 , K 4 of the springs (in units of N / m) are
respectively taken from cells G5, H5, I5, J5. The value of force f (in newtons) is
taken from G6; constant C is taken from H6.
According to Fig. 6.21a:
the initial values of variables x1 , x 2 , x 3 are equal to zero;
459
Chapter 6. Numerical Methods for Nonlinear Programming
Fig. 6.21. The Sheet2 worksheet (a) before and (b) after the code execution
460
6.6. Determining the equilibrium state of a four-spring system
The use of the Powell method for the minimization of function (6.13) is not
difficult. For this purpose, we have to replace mini with minim in operator 3.
Upon the change in the minimization method, only the number of the calcu-
lated values of objective function (6.13) changes markedly — from 88 to 95.
The above minimization problem is the only one in this chapter whose solu-
tion by the Powell method is not more efficient than by the coordinate-descent
method.
461
Chapter 6. Numerical Methods for Nonlinear Programming
462
6.7. Minimization with nonlinear constraints
It is visible that variables x1 and x 2 satisfy the required inequalities, (6.15) and
(6.16), for all values of 1
and 2
from to . Substituting expressions
(6.17) and (6.18) into formula (6.1), we get the following objective function:
2 2 2 4
G( 1
, 2
) 100[0.7 sin 2
(1 1
) ] 1
. (6.19)
Sub main()
Dim x() As Double
Dim ss() As Double
Dim n As Byte
Dim i As Byte, j As Byte
Dim d As Double
n = 2 'number of variables
ReDim x(n)
ReDim ss(1 To n, 1 To n)
For j = 1 To n
x(j) = Worksheets("Sheet2").Cells(1, 6 + j)
For i = 1 To n
ss(i, j) = Worksheets("Sheet2"). _
Cells(1 + i, 6 + j)
Next i
Next j
For j = 1 To n
d = 0
For i = 1 To n
d = ss(i, j) ^ 2 + d
Next i
If d = 0 Then
Range("Sheet2!A1").Value = _
"You must increase" & Str(j) & _
463
Chapter 6. Numerical Methods for Nonlinear Programming
464
6.7. Minimization with nonlinear constraints
From code Listing 6.4 for solving the minimization problem without con-
straints, the above code differs in the following:
in operators of the func subroutine because it is now intended for calcu-
lating values of objective function G ( 1 , 2 ) according to formula (6.19)
instead of (6.1);
in operator 1 because we use the Powell method in the new program;
in the presence of operators 2 and 3, which correspond to formulas (6.17)
and (6.18), respectively.
After obtaining the values of 1
and 2
, operators 2 and 3 calculate the
values of x1 and x 2 , i.e., the solution of the minimization problem for the
Rosenbrock function with constraints (6.15) and (6.16).
Fig. 6.22 shows the Sheet2 worksheet upon termination of the code execu-
tion.
465
Chapter 6. Numerical Methods for Nonlinear Programming
1
= - 0.403 and 2
= 7.854;
the required values are x1 = 0.837 and x 2 = 0.7; they are located in cells
B14 and C14.
When replacing minim with mini in operator 1 (that is, when using the
coordinate-descent method) the number of iterations increases from 13 to 254,
and the number of the calculated values of objective function G ( 1 , 2 )
increases from 505 to 2372.
The application of the variable replacement method, which was considered,
is very limited. For minimizing nonlinear function F ( x1 , x2 , ..., xn ) with con-
straints (6.14), the penalty function method is more universal. According to this
method, functions
Gk ( x) F ( x) 2 k [ D1 ( x) D2 ( x) ... Dm ( x)] (6.20)
of vector argument x ( x1 , x 2 , ..., x n ) , k ≥ 0, are being sequentially mini-
mized for k = 0, 1, 2, ... The value of k determines the “weight” of sum
D1 ( x) D2 ( x) ... Dm ( x) , i.e., its contribution to the G k (x ) function; m is
the number of the constraints.
We use formula
Di (x) min{Cip (x), 0} ,
where the p power is an odd natural number, for example 3, 1 ≤ i ≤ m.
According to the last formula:
Di (x ) 0 when Ci (x) 0 , i.e., the i-th inequality of (6.14) is satisfied;
Di (x) Cip (x) 0 when Ci (x) 0 , i.e., the i-th inequality of (6.14) is
unsatisfied.
We can combine functions (6.20) into the following single function with
additional argument x n 1 :
G ( x , xn 1
) F ( x) xn 1
[ D1 ( x) D2 ( x) ... Dm ( x)] . (6.21)
The original problem with constraints is reduced to a sequence of problems
without constraints: we must find the minimum point of each of functions
G0 ( x ) G ( x, 1) , G1 ( x) G ( x, 2) , G2 ( x) G ( x, 4) , ..., Gk ( x) G (x, 2k ) , ...
466
6.7. Minimization with nonlinear constraints
Gk (x) G (x, 2k ) .
of required x .
Functions (6.20) are called the penalty functions. Let also:
function (6.21) of form
G ( x1 , x2 , ..., xn , xn 1 ) F ( x) xn 1[ D1 ( x) D2 ( x) ... Dm ( x)]
be called the penalty function;
summand xn 1[ D1 ( x) D2 ( x) ... Dm ( x)] be called the penalty.
The penalty function method allows to solve the minimization problem for
Rosenbrock function (6.1) with constraint x12 x22 1 , which can be written in
form (6.14),
C1 ( x1 , x2 ) 0 , (6.22)
where
C1 ( x1 , x2 ) x12 x22 1 . (6.23)
To use the Powell method for minimizing function (6.1) with this constraint,
we must enter the following code into Module1.
Listing 6.8
Const DBL_MAX = 1E+308
Dim nf As Long 'counter of calls of func
Dim nt As Long 'counter of calls of test
Dim m As Byte
Dim y0 As Double, z0 As Double
467
Chapter 6. Numerical Methods for Nonlinear Programming
Sub main()
Dim x() As Double
Dim ss() As Double
Dim n As Byte, i As Byte, j As Byte
Dim d As Double
n = 2 'number of variables
m = 1 'number of constraints
ReDim x(-1 To n + m)
ReDim ss(1 To n, 1 To n)
For j = 1 To n
x(j) = Worksheets("Sheet2").Cells(1, 6 + j)
For i = 1 To n
ss(i, j) = Worksheets("Sheet2"). _
Cells(1 + i, 6 + j)
Next i
Next j
For j = 1 To n
d = 0
For i = 1 To n
d = ss(i, j) ^ 2 + d
Next i
If d = 0 Then
Range("Sheet2!A1").Value = _
"You must increase" & Str(j) & _
"-th initial step"
End
End If
Next j
nf = 0
nt = 0
x(n + 1) = 1
Call func(n, x) 'it must be before minimization
z0 = x(0): y0 = DBL_MAX
1: Call minim(n, x, ss, 1E-3, 1E-6)
End Sub
468
6.7. Minimization with nonlinear constraints
Else
x(-1) = x(3) * (-c ^ 3) 'penalty, p = 3
End If
x(0) = 100 * (x(2) - x(1) ^ 2) ^ 2 + _
(1 - x(1)) ^ 2 + x(-1)
End Sub
The results of the code execution are depicted in Fig. 6.23. As we see, initial
approximation x 0 , defined by the values of cells G1 and H1, has coordinates
469
Chapter 6. Numerical Methods for Nonlinear Programming
x10 = -5.5 and x 20 = 0.5. According to the contents of cells G2:H3, the initial
steps are directed along the x1 and x 2 axes and equal 0.01.
Fig. 6.23. The Sheet2 worksheet upon termination of the code execution
x3 2 k . Column F contains the current value of nf, i.e., the current number of
the func subroutine calls. The coordinates of the obtained minimum point, x ,
are equal to x1 = 0.787 and x 2 = 0.62.
470
6.7. Minimization with nonlinear constraints
When replacing minim with mini in operator 1 (that is, when using the
coordinate-descent method), the number of iterations increases from 26 to 153,
and the number of the calculated values of the objective function increases from
385 to 1313.
The penalty function method allows solving the minimization problem for the
F ( x1 , x2 , ..., xn ) function when the equality type constraints are present among
constraints (6.14); for example, C1 ( x1 , x2 , ..., xn ) 0 may be the first con-
straint. In this case, we use D1 (x) C1q (x) in expressions (6.20) and (6.21),
where power q is an even natural number, for example 2.
As an example of using this form of the penalty function method, we will
consider the minimization problem for Rosenbrock function (6.1) with constraint
x12 x22 1 , which can be written as follows:
C1 ( x1 , x2 ) 0,
and equal 0.01. The coordinates of the obtained minimum point, x , are equal to
x1 = 0.786 and x 2 = 0.618. When replacing the minim subroutine with mini,
471
Chapter 6. Numerical Methods for Nonlinear Programming
the number of iterations increases from 18 to 67, the number of the calculated
values of the penalty function increases from 347 to 686.
Besides the above methods, the barrier function method is used for the
F (x) function minimization with nonlinear constraints. It differs from the penal-
ty function method in the form of the second summand in formula (6.20):
k
Gk (x) F ( x) 2 [1 / C1p (x) 1 / C2p (x) ... 1 / Cmp (x)] , (6.24)
where p is an even natural number. The G ( x, xn 1
) function has the following
form:
G(x, xn 1
) F ( x) xn 1 1[1 / C1p (x) 1 / C2p (x) ... 1 / Cmp (x)] . (6.25)
Summand xn 1 1[1 / C1p (x) 1 / C2p (x) ... 1 / Cmp (x)] is called the barrier; func-
tions (6.24) and (6.25) are called the barrier functions.
As we see, function (6.25) is close to (6.21) in form. Therefore, the new code
for minimizing function (6.1) with constraint (6.22), (6.23) by the Powell method
differs from Listing 6.8 only in the following operator:
472
6.7. Minimization with nonlinear constraints
equal 0.01. The coordinates of the obtained minimum point, x , are equal to
x1 = 0.786 and x2 = 0.616. When replacing minim with mini in operator 1,
the number of iterations increases from 60 to 314, and the number of the calcu-
lated values of the barrier function increases from 703 to 2552.
Let us solve one more minimization problem for Rosenbrock function (6.1),
when constraint x12 x22 1 is imposed on the minimum point. This inequality
473
Chapter 6. Numerical Methods for Nonlinear Programming
For minimizing function (6.1) with this constraint by the penalty function and
Powell methods, we use Listing 6.8 with minim in operator 1 and the following
func subroutine:
Listing 6.10
Sub func(ByVal n, ByRef x() As Double)
Dim c As Double
nf = nf + 1
c = x(1) ^ 2 + x(2) ^ 2 - 1
2: If c >= 0 Then
x(-1) = 0
Else
x(-1) = x(3) * (-c ^ 3) 'penalty, p = 3
End If
x(0) = 100 * (x(2) - x(1) ^ 2) ^ 2 + _
(1 - x(1)) ^ 2 + x(-1)
End Sub
Fig. 6.26 shows the results of using the last version of code Listing 6.8.
Fig. 6.26. The Sheet2 worksheet upon termination of the code execution
474
6.8. Minimization of the multimodal function
Sub main()
Dim x() As Double
Dim ss() As Double
475
Chapter 6. Numerical Methods for Nonlinear Programming
Dim n As Byte
Dim i As Byte, j As Byte
Dim d As Double
Dim sec As Long
Dim min As Byte, hour As Byte
Dim st As String
Dim stp As Date
Dim np_lim As Long
n = 2 'number of variables
ReDim x(n)
ReDim ss(1 To n, 1 To n)
1: sec = Range("Sheet2!G4").Value
2: hour = sec \ 3600
3: min = (sec - hour * 3600) \ 60
4: sec = sec - hour * 3600 - min * 60
5: st = CStr(hour) & ":" & CStr(min) & ":" _
& CStr(sec)
6: stp = Now + TimeValue(st)
7: np_lim = Range("Sheet2!H4").Value
8: Randomize 'it must be before calling Rnd
9: np = 0
beg:
10: np = np + 1
11: x(1) = 0.5 + (5.5 - 0.5) * Rnd
12: x(2) = 0.5 + (5 - 0.5) * Rnd
For j = 1 To n
For i = 1 To n
ss(i, j) = Worksheets("Sheet2"). _
Cells(1 + i, 6 + j)
Next i
Next j
For j = 1 To n
d = 0
For i = 1 To n
d = ss(i, j) ^ 2 + d
Next i
If d = 0 Then
Range("Sheet2!A1").Value = _
"You must increase" & Str(j) & _
"-th initial step"
End
End If
476
6.8. Minimization of the multimodal function
Next j
nf = 0
nt = 0
Call func(n, x) 'it must be before minimization
Call minim(n, x, ss, 1E-6, 1E-6) 'Powell method
13: For j = 0 To n
14: Worksheets("Sheet2").Cells(np, j + 1) = x(j)
15: Next j
16: Worksheets("Sheet2").Cells(np, n + 2) = nt
17: Worksheets("Sheet2").Cells(np, n + 3) = nf
18: If Now < stp And np < np_lim And np < 1048576 _
Then GoTo beg
End Sub
From code Listing 6.4, intended for minimizing the Rosenbrock function,
the last code differs in operators of the func subroutine and presence of opera-
tors 1 — 18 in the main program. Let us consider the purpose of these addi-
tional operators.
Operator 1 assigns the specified limiting execution time (in seconds), being
in cell Sheet2!G4, to variable sec of the Long data type. Operators 2 — 5
form the st string of format "hh:mm:ss", in which hh is one or two digits
477
Chapter 6. Numerical Methods for Nonlinear Programming
The x 0 point falls into any place of rectangle 0.5 x1 5.5 and
0 .5 x2 5 with equal probability.
Below operator 12, we see familiar operators of the function minimization
by the Powell method. Upon termination of the minim subroutine execution,
operators 13 — 18 are performed.
Operators 13 — 17 put the result of searching the local minimum into the
empty row on the Sheet2 worksheet. The result includes:
x(0) — the value of function F ;
x(1), x(2) — the values of arguments x1 and x 2 ;
nt, nf — the numbers of the test and func calls required for finding
the local minimum.
Operator 18 performs the jump to label beg if the following three conditions
are satisfied simultaneously:
the execution time is less than the limiting time;
the number of found minimum points is less than the limiting number;
empty rows still stay on the Excel worksheet.
After the jump to label beg, the new x 0 point is defined randomly and the
minimization is repeated.
Fig. 6.27 shows the beginning of the Sheet2 worksheet after the code execu-
tion. The limiting execution time and the limiting number of found minimum
points are equal to 1 second and 100, respectively. During the code execution,
100 minimum points were calculated; coordinates of seven of them are given in
table “The minimization results” below. The 93 remaining points practically
478
6.8. Minimization of the multimodal function
coincide with these seven points or are outside the domain defined by inequali-
ties 0.5 x1 5.5 and 0.5 x2 5 .
Minimum’s number x0 F ( x1 , x2 ) x1 x2
1 0 1.57 1.57
2 0 4.71 1.57
3 0 4.71 4.71
4 0 1.57 4.71
5 0 1 1
6 0.397 2.13 4.54
7 0.732 1.88 3.55
When creating table “The minimization results”, we applied the Excel filter
to the worksheet of Fig. 6.27 as follows:
1) set the number format with two decimal places for columns B and C;
2) select columns A:E;
3) Data > Filter in area Sort & Filter (Fig. 6.28);
479
Chapter 6. Numerical Methods for Nonlinear Programming
4) in the first row of the B column, fulfill Number Filters > Custom Filter by
means of the drop-down list;
5) in the Custom AutoFilter window opened, set the following: ≥ 0.5 and ≤
5.5 (Fig. 6.29);
6) click on the OK button;
7) in the first row of the C column, fulfill Number Filters > Custom Filter;
8) in the Custom AutoFilter window opened, set the following: ≥ 0.5 and ≤ 5
(Fig. 6.30);
9) click on the OK button.
The first four minima in table “The minimization results” are located at the
points, where the first multiplicand of objective function (6.26) is equal to zero:
cos2 x1 cos2 x2 0
480
6.8. Minimization of the multimodal function
Fig. 6.29. Setting the constraints for x1 during the filter usage
Fig. 6.30. Setting the constraints for x 2 during the filter usage
481
Chapter 6. Numerical Methods for Nonlinear Programming
Strictly speaking, the above method for minimizing the multimodal function
does not guarantee finding all local minima inside the function’s domain. How-
ever, the probability of this is close to unity if the code execution is sufficiently
long.
Often, we do not believe in the adequacy of the obtained solution of a mini-
mization problem, even when we know that the objective function is unimodal.
In this case, the use of this section’s method is a good idea.
We advise the reader to write a program for finding the global minimum of
function
F ( x1 , x2 ) f12 ( x1 ) f 22 ( x2 )
inside rectangle a1 x1 b1 and a2 x2 b2 , where f1 ( x1 ) and f 2 ( x2 ) are
functions from Appendix 4, segments [ a1 , b1 ] and [ a2 , b2 ] are the domains of
functions f1 ( x1 ) and f 2 ( x2 ) , respectively.
In addition, we advise the reader to use the random-number generator for
defining both the initial approximation of the minimum point and the initial steps
along the x1 and x 2 axes.
By the way, the last minimum in table “The minimization results” (with co-
ordinates x1 = 1.88 and x 2 = 3.55) is the solution of the following maximin
problem: to determine the maximum value of function (6.26) among the local
minima inside rectangle 0.5 x1 5.5 and 0.5 x2 5 . The global minimum
is equal to zero; it is reached at the first five minimum points.
482
6.9. Minimization of the tabular function
483
Chapter 6. Numerical Methods for Nonlinear Programming
Listing 6.13
Const DBL_MAX = 1E+308
Dim x1() As Double 'grid nodes on axis x1
Dim x2() As Double 'grid nodes on axis x2
Dim k As Integer 'number of segments on x1
Dim r As Integer 'number of segments on x2
Dim ff() As Double 'values of function F
Dim f1() As Double 'values of splines
Dim f2() As Double 'values of function of x2
Dim mm() As Double 'values of moments about x2
Dim m1() As Double 'values of moments about x1
484
6.9. Minimization of the tabular function
Sub main()
Dim x(2) As Double
Dim ss(1 To 2, 1 To 2) As Double
Dim i As Integer, j As Integer
Dim min As Double
k = Selection.Rows.Count - 2
r = Selection.Columns.Count - 2
ReDim x1(k)
ReDim x2(r)
ReDim ff(k, r)
ReDim f1(k)
ReDim f2(r)
ReDim mm(k, r)
ReDim m1(k)
ReDim m2(r)
For i = 0 To k
x1(i) = Selection.Cells(2 + i, 1)
Next i
For j = 0 To r
x2(j) = Selection.Cells(1, 2 + j)
Next j
For i = 0 To k
For j = 0 To r
ff(i, j) = Selection.Cells(2 + i, 2 + j)
Next j
Next i
'Calculation of 2D array of moments about x2:
For i = 0 To k
For j = 0 To r
f2(j) = ff(i, j)
Next j
0: Call mos(0, r, x2, f2, 0, 0, 0, 0, m2)
For j = 0 To r
mm(i, j) = m2(j)
Next j
Next i
'Specifying initial approximation of minimum point:
485
Chapter 6. Numerical Methods for Nonlinear Programming
min = DBL_MAX
For i = 0 To k
For j = 0 To r
If ff(i, j) < min Then
min = ff(i, j)
x(1) = x1(i)
x(2) = x2(j)
End If
Next j
Next i
no = i + 2
'Specifying initial steps:
ss(1, 1) = 0.01: ss(1, 2) = 0
ss(2, 1) = 0: ss(2, 2) = 0.01
'Searching minimum point:
nf = 0
nt = 0
Call func(2, x) 'it must be before minimization
Selection.Cells(no, 1) = x(0)
Selection.Cells(no, 2) = x(1)
Selection.Cells(no, 3) = x(2)
Call minim(2, x, ss, 1E-6) 'Powell method
'Outputting minimum point:
Selection.Cells(no + 1, 1) = x(0)
Selection.Cells(no + 1, 2) = x(1)
Selection.Cells(no + 1, 3) = x(2)
Selection.Cells(no + 1, 4) = nt
Selection.Cells(no + 1, 5) = nf
End Sub
486
6.9. Minimization of the tabular function
We enter this code into Module1 of the BookNM workbook. The source data
are in the Excel table (Fig. 6.31); this table (range B2:G13) should be selected
before the code execution.
Let us consider the three main stages of the code execution.
First of all, the moments of cubic splines S 0 ( x 2 ) , S1 ( x 2 ) , . . . , S k ( x 2 ) ,
defined by grid functions f 0 ( x2 ) F ( x1,0 , x2 ) , f1 ( x2 ) F ( x1,1 , x2 ) , . . . ,
f k ( x2 ) F ( x1, k , x2 ) , are calculated by means of operator 0:
f 0 ( x2 ) and S 0 ( x 2 ) correspond to range C3:G3;
f1 ( x2 ) and S1 ( x 2 ) correspond to range C4:G4;
f k ( x2 ) and S k ( x2 ) correspond to range C13:G13.
These moments are stored in two-dimensional array mm. Later this array is used
(by means of one-dimensional array m2) in the func subroutine for the spline
interpolation (operator 1).
Further, coordinates x(1) and x(2) of initial approximation x 0 of the x
minimum point are specified as follows:
the minimum of range C3:G13 (Fig. 6.31) is found: min = 1.026724
(cell F10);
the point, where function F equals min, is taken as the initial approxima-
tion: x(1) = 3.4, x(2) = 0.6.
487
Chapter 6. Numerical Methods for Nonlinear Programming
488
6.9. Minimization of the tabular function
x(0) = 0
= F( 1
,
2
) = S( 1
).
According to Fig. 6.32, the found minimum point of the F ( x1 , x 2 ) function,
given by table Listing 6.12, has coordinates x1 = 3.111 and x 2 = 0.525, and the
f r ( x1 ) F ( x1 , x 2, r ) :
489
Chapter 6. Numerical Methods for Nonlinear Programming
d 2u du
F x, u , , (6.27)
dx 2 dx
u ( a) A , (6.28)
u (b) B , (6.29)
where A and B are given parameters, F is a nonlinear function of variables x, y
and z.
Problem (6.27) — (6.29) was solved by the quasilinearization method in Sec-
tion 3.12. Below, this problem will be solved by the shooting method.
We introduce unknown function
du
v( x) .
dx
This expression can be written in the following equation form:
du
E ( x, u , v ) , (6.30)
dx
where E is a function of simple form: E v .
Equation (6.27) becomes
dv
F ( x, u , v ) . (6.31)
dx
In Section 5.2, the method for solving the system of equations (6.30) and
(6.31) was developed for initial conditions (6.28) and
v( a) Q . (6.32)
According to the shooting method, problem (6.27) — (6.29) can be solved by
the repeated solution of system (6.30), (6.31) with initial conditions (6.28) and
(6.32) for different values of Q until satisfaction of condition (6.29) at point b.
Let us consider the shooting model, which is a good illustration of the shoot-
ing method (this explains the method name).
490
6.10. Solving the nonlinear differential equation by the shooting method
If we neglect the air resistance, then Newton’s second law gives the projectile
trajectory, u (x) , described by equation (6.27), where
F g (1 Q 2 ) / V 2 .
In this expression:
du
Q (a) is the slope of the gun barrel located at point ( a, A) with
dx
coordinates x = a and u = A;
V is the projectile velocity at the moment of leaving the barrel;
g is the free fall acceleration.
Let us assume that the target is at point (b, B) with coordinates x = b and
u = B. Solving the system of equations (6.30) and (6.31) with initial conditions
(6.28) and (6.32) at various values of Q, we simulate the shooting when varying
the slope of the gun barrel (Fig. 6.33).
Fig. 6.33. Graphic image of the u (x) solution of system (6.30), (6.31)
with initial conditions (6.28) and (6.32) at two values of Q
To obtain slope Q , at which the projectile hits the target at point (b, B), we
have to solve algebraic equation
u (Q, b) B , (6.33)
where u(Q, x) is the result of solving the system of differential equations (6.30)
and (6.31) with initial conditions (6.28) and (6.32) at given Q.
491
Chapter 6. Numerical Methods for Nonlinear Programming
492
6.11. Modeling of the hammer motion in the piano mechanism
As an example of using the shooting method, we will solve the following task
of modeling of the hammer motion in the piano mechanism when rupture of the
spring occurs:
in addition to the initial time moment, a = 0, of rupture of the spring,
another moment, b = 20 ms, is given;
we know that the hammer’s displacement forward is equal to A3 = 7 mm
and B3 = 15 mm at moments a and b, respectively;
we have to determine values A4 and B4 of the hammer velocity at these
moments.
For solving this task, we use the simplified mathematical model of the piano
mechanism: the elastic constant of the spring, k, equals zero in model (5.27) —
(5.30). In this case, the hammer’s displacement is described by equation
d 2 u3 du3
E4 u3 , , (6.36)
dt 2 dt
where
2
du3
q
du3 dt
E4 u3 , .
dt p qu3
Second-order nonlinear differential equation (6.36) is considered on time
segment 0 ≤ t ≤ b. We have to solve this equation with boundary conditions
u 3 (0) A3 , (6.37)
u 3 (b ) B3 . (6.38)
As in Section 5.6, let us introduce the hammer velocity, u 4 du3 / dt . We
obtain the following system of first-order differential equations:
du3
E3 ( u 4 ) , (6.39)
dt
493
Chapter 6. Numerical Methods for Nonlinear Programming
du4
E4 ( u3 , u 4 ) , (6.40)
dt
where
E3 u4 ,
qu 42
E4 .
p qu3
According to the shooting method, boundary value problem (6.36) — (6.38)
can be solved by the repeated solution of the system of differential equations
(6.39) and (6.40) with initial conditions (6.37) and
u 4 (0) A4 . (6.41)
For obtaining desired value A4 of the hammer velocity at the initial time
moment, we have to minimize the following function similar to (6.34):
G( A4 ) [u3 ( A4 , b) B3 ]2 , (6.42)
where function u3 ( A4 , t ) is the result of solving the system of equations (6.39)
and (6.40) with initial conditions (6.37) and (6.41) at given A4 .
Function (6.42) will be minimized by the mini subroutine. We could use the
minim subroutine because mini and minim work equally in the case of a one-
variable function (n = 1).
In the source data table given below, values l, τ, p, q and ζ have the same
sense as in table Listing 5.3 (p. 376).
Listing 6.14
l 20
tau 1.00E-03
A4 0
p 0.406
q 18.3
zeta 1.00E-09
A3 0.007
B3 0.015
494
6.11. Modeling of the hammer motion in the piano mechanism
Sub main()
Dim ss(1 To 1, 1 To 1) As Double
Dim i As Integer
Dim sb As String, se As String
l = Selection.Cells(1, 2)
tau = Selection.Cells(2, 2)
A4 = Selection.Cells(3, 2)
p = Selection.Cells(4, 2)
q = Selection.Cells(5, 2)
zeta = Selection.Cells(6, 2)
A3 = Selection.Cells(7, 2)
B3 = Selection.Cells(8, 2)
tau2 = tau / 2
ReDim uu(1 To 4, 0 To l)
ReDim jj(0 To l)
x(1) = A4 'initial approximation of A4
ss(1, 1) = 1E-6 'initial step along A4 axis
nf = 0: nt = 0
Call func(1, x) 'it must be before minimization
Call mini(1, x, ss, 1E-12, 1E-12)
MsgBox "A4 = " & CStr(Round(x(1), 3)) & " m/s"
MsgBox "B4 = " & CStr(Round(uu(4, l), 3)) & " m/s"
Selection.Cells(9, 1) = "t"
495
Chapter 6. Numerical Methods for Nonlinear Programming
Selection.Cells(9, 2) = "u3"
Selection.Cells(9, 3) = "u4"
Selection.Cells(9, 4) = "j max"
For i = 0 To l 'movement along time axis
Selection.Cells(10 + i, 1) = i * tau
Selection.Cells(10 + i, 2) = uu(3, i)
Selection.Cells(10 + i, 3) = uu(4, i)
Selection.Cells(10 + i, 4) = jj(i)
12: Selection.Cells(10 + i, 4). _
HorizontalAlignment = xlCenter 'alignment
Next i
sb = Selection.Cells(10, 1).Address
se = Selection.Cells(10 + l, 2).Address
13: Call graph(sb, se, "t, s", "u3, m")
End Sub
496
6.11. Modeling of the hammer motion in the piano mechanism
nf = nf + 1
1: u(3) = A3: u(4) = x(1) 'values at t=0
For m = 3 To 4
uu(m, 0) = u(m)
Next m
jj(0) = 0
For i = 1 To l 'movement along time axis
2: Call e_functions(u, e)
For m = 3 To 4
3: alpha(m) = u(m) + tau2 * e(m)
4: xx(m) = u(m) + tau * e(m)
Next m
For j = 1 To 1000 'Newton iterations
5: Call fx_jacobian(xx, a)
6: Call e_functions(xx, e)
For m = 3 To 4
7: b(m) = alpha(m) - _
(xx(m) - tau2 * e(m))
Next m
8: Call gauss(2, a, b, z, 2, 2)
For m = 3 To 4
9: xx(m) = xx(m) + z(m)
Next m
max = 0
For m = 3 To 4
If Abs(z(m)) > max Then _
max = Abs(z(m))
Next m
10: If max < zeta Then Exit For
Next j
For m = 3 To 4
11: u(m) = xx(m)
uu(m, i) = u(m)
Next m
jj(i) = j
Next i
14: x(0) = (u(3) - B3) ^ 2
End Sub
497
Chapter 6. Numerical Methods for Nonlinear Programming
nt = nt + 1
If Abs(z(0) - x(0)) < n * rho * z(0) Then
test = False
Else
test = True
End If
If Not IsMissing(alpha) Then
If x(0) < alpha Then test = False
End If
If n = 1 Or nt = 1048576 Then test = False
End Function
498
6.11. Modeling of the hammer motion in the piano mechanism
3) after clicking on button OK, the following results, depicted in Fig. 6.37,
appear:
the values of t, u 3 and u 4 ;
the numbers of the Newton iterations, j max ;
the graph of dependence u 3 (t ) .
The last graph is the result of the graph subroutine execution (operator 13).
On p. 328, we used Fig. 6.37 to demonstrate the features of this subroutine
intended for automatic creation of graphs.
In section “Instead of Conclusions”, we will need the dependences of the cal-
culated values of A4 and B 4 versus the number of steps on segment 0 ≤ t ≤ b.
These dependences, depicted in Fig. 6.38, were obtained by executing code
Listing 6.15 for l = 2, 3, 5, 10, 20, 30. The time step is equal to b / l , where
b = 0.02.
499
Chapter 6. Numerical Methods for Nonlinear Programming
Fig. 6.37. The code execution results, which include the u 3 (t ) graph
500
6.12. Nonlinear programming and the least-squares method
G ( L1 , ..., L , ..., Ln ) [ L( x j ) u j ] 2 .
j 1
In Section 5.9, we minimized this function by solving the system of linear alge-
braic equations (5.48). In this section, we will use the Powell method for the
minimization.
Below is a code for finding required values L1 , ..., L , ..., Ln .
Listing 6.16
Dim nf As Long 'counter of calls of func
Dim nt As Long 'counter of calls of test
Dim m As Integer
Dim XX() As Double
Dim UU() As Double
Dim ZZ() As Double
Sub main()
Dim x() As Double
Dim ss() As Double
Dim n As Integer
Dim i As Integer
Dim j As Integer
Dim d As Double
m = Selection.Rows.Count 'quantity of rows
n = Selection.Cells(1, 2) 'number of nodes
501
Chapter 6. Numerical Methods for Nonlinear Programming
ReDim XX(3 To m)
ReDim UU(3 To m)
ReDim ZZ(1 To n)
ReDim x(n)
ReDim ss(1 To n, 1 To n)
For j = 3 To m
XX(j) = Selection.Cells(j, 1)
UU(j) = Selection.Cells(j, 2)
Next j
For i = 1 To n
ZZ(i) = Selection.Cells(2 + i, 3)
Next i
For j = 1 To n
x(j) = Cells(1, 6 + j)
For i = 1 To n
ss(i, j) = Cells(1 + i, 6 + j)
Next i
Next j
For j = 1 To n
d = 0
For i = 1 To n
d = ss(i, j) ^ 2 + d
Next i
If d = 0 Then
Cells(1, 1).Value = _
"You must increase" & Str(j) & _
"-th initial step"
End
End If
Next j
nf = 0
nt = 0
Call func(n, x) 'it must be before minimization
0: Call minim(n, x, ss, 1E-6) 'Powell method
'Output of results:
For j = 0 To n
Selection.Cells(m + 2, j + 1) = x(j)
Next j
Selection.Cells(m + 2, n + 2) = nt
Selection.Cells(m + 2, n + 3) = nf
Selection.Cells(2, 4) = "L"
For i = 1 To n
502
6.12. Nonlinear programming and the least-squares method
Selection.Cells(2 + i, 4) = x(i)
Next i
End Sub
503
Chapter 6. Numerical Methods for Nonlinear Programming
According to Fig. 6.40, four iterations were performed and 104 values of
objective function (5.43) were calculated during the minimization by the Powell
method (by means of the minim subroutine, see operator 0). The calculated
values L1 , L2 , L3 of the linear spline at grid nodes z1 < z 2 < z 3 are respec-
tively placed in cells E4, E5 and E6 (and also in cells C17, D17 and E17). Natu-
rally, these values are the same as when using program Listing 5.6.
When using the minim subroutine in the least-squares method, we can easily
switch to another form of the required functional dependence, for example, to
quadratic form
F (C1 , C2 , C3 , x) C1 C2 x C3 x 2 . (6.43)
The values of constants C1 , C 2 and C3 must be determined by minimizing the
following non-negative function similar to (5.42):
504
6.12. Nonlinear programming and the least-squares method
where x j and u j are the values given in columns Mark and Productivity of the
source data table depicted in Fig. 6.39, 1 ≤ j ≤ ν (ν = 12 is the number of land
plots).
Listing 6.17
Dim nf As Long 'counter of calls of func
Dim nt As Long 'counter of calls of test
Dim m As Integer
Dim XX() As Double
Dim UU() As Double
Sub main()
Dim x() As Double
Dim ss() As Double
Dim n As Integer
Dim i As Integer
Dim j As Integer
505
Chapter 6. Numerical Methods for Nonlinear Programming
Dim d As Double
m = Selection.Rows.Count 'quantity of rows
n = Selection.Cells(1, 2) 'number of nodes
ReDim XX(3 To m)
ReDim UU(3 To m)
ReDim x(n)
ReDim ss(1 To n, 1 To n)
For j = 3 To m
XX(j) = Selection.Cells(j, 1)
UU(j) = Selection.Cells(j, 2)
Next j
For j = 1 To n
x(j) = Cells(1, 6 + j)
For i = 1 To n
ss(i, j) = Cells(1 + i, 6 + j)
Next i
Next j
For j = 1 To n
d = 0
For i = 1 To n
d = ss(i, j) ^ 2 + d
Next i
If d = 0 Then
Cells(1, 1).Value = _
"You must increase" & Str(j) & _
"-th initial step"
End
End If
Next j
nf = 0
nt = 0
Call func(n, x) 'it must be before minimization
0: Call minim(n, x, ss, 1E-6) 'Powell method
'Output of results:
For j = 0 To n
Selection.Cells(m + 2, j + 1) = x(j)
Next j
Selection.Cells(m + 2, n + 2) = nt
Selection.Cells(m + 2, n + 3) = nf
Selection.Cells(2, 4) = "C"
For i = 1 To n
Selection.Cells(2 + i, 4) = x(i)
506
6.12. Nonlinear programming and the least-squares method
Next i
End Sub
507
Chapter 6. Numerical Methods for Nonlinear Programming
E4, E5 and E6 (and also in cells C17, D17 and E17). Fig. 6.43 shows the graph
of quadratic dependence (6.43) with the calculated constants:
F (C1 , C2 , C3 , x) C1 C2 x C3 x 2 ,
508
6.12. Nonlinear programming and the least-squares method
Fig. 6.43. The experimental points and the quadratic line of the functional
dependence of the wheat productivity on the land quality mark
509
Instead of Conclusions
510
Instead of Conclusions
511
Instead of Conclusions
512
Appendix 1.
Data Types of Visual Basic and VBA
513
Appendix 1. Data Types of Visual Basic and VBA
1 B per character
for string of String length from 1 to 216 characters
fixed length
16 B
if the choice by
context gives
data type Values correspond to the Boolean,
Boolean, Byte, Byte, Integer, Long,
Integer, Long, Currency, Single, Double or
Currency, Date data type
Variant
Single, Double
or Date
22 B +
1 B per character Values correspond to String of
if the choice variable length
is not made
The memory cell stores the object
Object 4B
reference
Depends
on the quantity
User-defined Created by the Type operator
of fields and
their data types
514
Appendix 2.
Greek and Russian Alphabets
Denoted by Latin Letters
515
Appendix 2. Greek and Russian Alphabets Denoted by Latin Letters
516
Appendix 3.
The Main Mathematical Functions
The Visual Basic operators for calculating the values of trigonometric func-
tion cot x , of inverse trigonometric functions arcsin x , arccos x and arccot x
and of decimal logarithm lg x are given below.
517
Appendix 4.
Material for Tasks
The table below, taken from [19], contains 31 functions f (x) and their
domains [a, b] with the following properties:
function f (x) is continuous and monotonous on segment [a, b] ;
the signs of f (x) on the left and right boundaries of [a, b] are different.
This table is used in tasks for the reader (the tasks begin with words “we
advise the reader”). The f (a) values, given in the table, are intended to help the
reader debug his programs.
By using this table, a teacher can create 31 variants of tasks for exams. The
variant number may be a student’s birthday.
No. of
Function f(x) a b f(a)
variant
1 (3.8 3 sin x ) / 0.35 x 2 3 0.3905776
2 1 0 0.85 0.3333333
[3 sin(3.6 x)] x
518
Appendix 4. Material for Tasks
No. of
Function f(x) a b f(a)
variant
14 0.4 arctan x x 1 2 0.1853982
15 x tan x 1 / 3 0.2 1 -0.2927913
2
16 tan(0.55x 0.1) x 0.4 1 0.171389
17 2 sin(1 / x) x 1.2 2 0.0598231
18 1 sin x ln(1 x) x 0 1.5 1
0.52
19 cos( x 2) x 0.5 1 0.4029458
20 ln(1 x) 3 x 2 3 0.024503
21 ex ln x 10x 3 4 -8.815851
22 x x 1 3 -8.649598
3x 14 e e
23 2 1 3 -5
2 ln x 6 ln x 5
24 2x sin x cos x 0.4 1 -0.6095263
25 cos x exp( x 2 / 2) x 1 1 2 -0.0662284
26 1 x tan x 0 0.9 1
27 sin( x 2 ) cos( x 2 ) 10 x 0 1 1
28 ex 1 e 2x 2 -1 0 -0.5665994
29 1 x cos 1 x 0 0.9 0.4596977
30 tan(x / 2) cot(x / 2) x 1 2 -0.2841852
31 x cos x 0.5 2.5 -0.3775826
519
Appendix 5.
Analytical Method for Solving
the Cubic Algebraic Equation
Below, we will present Method 3 of handbook [3] for solving cubic equation
z3 3 p z 2q 0 , where p and q are nonzero real numbers.
p 0
q 2 p3 0 q 2 p3 0 p 0
or 0 1 or 1
arccos Arcosh Arsinh
1 2
2 ln 2 1
arctan ln 1
z1 2r cos z1 2r ch z1 2r sh
3 3 3
z2 2r cos z2 r ch i 3 r sh z2 r sh i 3 r ch
3 3 3 3 3
z3 2r cos z3 r ch i 3 r sh z3 r sh i 3 r ch
3 3 3 3 3
As we see, the above formulas for calculating the roots depend on the signs
of p and q 2 p3 (i is the imaginary unit). The following mathematical functions
are used:
ch, sh — the hyperbolic cosine and sine:
ch x cosh x (e x e x ) / 2 , sh x sinh x (e x e x ) / 2 ;
Arcosh, Arsinh — the area-hyperbolic cosine and sine.
520
Appendix 6.
Realization of the Tangent Method
by Using the Excel Circular Reference
=G2-COS(G2)-1.5
=1+SIN(G2)
521
Appendix 6. Realization of the Tangent Method by Using the Excel Circular Reference
=G2-F2/E2
522
References List
1. G. Z. Garber, Bases of Programming in Visual Basic and VBA for Excel 2007
(in Russian), Moscow: SOLON-PRESS, 2008.
2. G. Z. Garber, Bases of Programming in VBA for Excel and of Numerical
Methods (in Russian), Moscow: PRINTKOM, 2009.
3. I. N. Bronshtein, K. A. Semendyayev, G. Musiol, H. Muehlig, Handbook of
Mathematics, 5th edition, Springer, 2007.
4. A. A. Samarskii, The Theory of Difference Schemes, Marcel Dekker, 2001.
5. T. Y. Na, Computational Methods in Engineering: Boundary Value Prob-
lems, Academic Press, 1979.
6. G. Z. Garber, E. V. Kostyukov, Yu. A. Kuznetsov, Two-dimensional model-
ing of a cell of photosensitive silicon charge-coupled device for color televi-
sion cameras (in Russian), Electronic Engineering. Series 2. Semiconductor
Devices, 1989, no. 3, pp. 40 – 44.
7. W. Shockley, Electrons and Holes in Semiconductors, with Applications to
Transistor Electronics, Van Nostrand Reinhold, 1950.
8. H. Gould, J. Tobochnik, An Introduction to Computer Simulation Methods:
Applications to Physical Systems, Addison-Wesley, 1988.
9. J. H. Ahlberg, E. N. Nilson, J. L. Walsh, The Theory of Splines and Their
Applications, Academic Press, 1967.
10. G. Z. Garber, Model for simulation of AlGaAs-GaAs power heterostructure
FETs, Proceedings of EUROCON 2005 – The International Conference on
“Computer as a Tool”, Belgrade: IEEE, 2005, vol. 1, pp. 867 – 870.
11. G. Z. Garber, Method for calculating a small-signal equivalent circuit of
extremely high frequency heterostructural field-effect transistors, Journal of
Communications Technology and Electronics, 2005, vol. 50, no. 7, pp. 822 –
825.
12. A. Oledzki, Dynamics of piano mechanisms, Mechanism and Machine Theo-
ry, 1972, vol. 7, pp. 373 – 385.
523
References List
524
Subject Index
A CCur 43
Abs 230, 517 CDate 43
Activate 161, 162, 167 CDbl 43
ActiveCell 148, 155, 156, 158, 174 Cells 148, 167, 169, 172, 173
ActiveChart 245 Charts 245
ActiveSheet 155, 168, 169, 245 CheckBox 125 – 127, 151
ActiveWorkbook 155, 162, 163 CInt 43, 44, 51, 153
Add 152, 162, 164, 167, 170, 245 Clear 172
Add Watch 19, 72, 73, 75 Clear All Breakpoints 19
Address 172, 174, 245 CLng 43
And 48 – 52 Close 102 – 104, 161, 164
Append 101, 102, 106, 108 Color 169
Application 148, 152, 154 – 160, 165 Columns 142, 172, 173, 188, 189
Array CommandButton 120, 151
static 68 Const 29, 30, 210
dynamic 71 Constant
As 23, 29, 77, 78, 81, 90, 101, 103 built-in 31
Atn 45, 315, 517 user-defined 29
Auto_Open 159, 160 Cos 46, 517
Average 154, 155 Count 142, 162, 168, 188, 189
Course
B backward 225
Boolean 23, 29, 43, 48, 439, 513 forward 225
ByRef 80 CSng 43
Byte 23, 24, 43, 513 CStr 43, 44, 96, 153
ByVal 80 Currency 23, 24, 27, 29, 43, 513
CVar 43
C Cycle
Calculate 158 Do…Loop 61
Calculation 156, 159 Do Until…Loop 62, 63, 103
Call 79 Do While…Loop 61, 62
Caption 117, 120, 121 Do…Loop Until 64
Case 56, 57 Do…Loop While 63
Case Else 57 For Each…Next 172
CBool 43 For…Next 58
CByte 43 While…Wend 61
525
Subject Index
F J
False 29, 48, 49, 126, 513 Jacobian matrix 364
fb 210, 211, 213
FileFormat 161 K
FileName 161 Kill 106
Fix 51, 517
foba 252, 253, 258 L
fobas 334, 335, 338, 347 Label 118, 151
Font 118, 156, 169 LBound 74, 75
For 58 – 60, 101, 103 LCase 96
For Each 172 Left 97, 98
forbac 262 – 264 Len 97
forbacs 266 Line Input 102, 103
Format 100, 170 LOF 103, 104
Formula 148, 171, 174 Log 45, 315, 517
FormulaR1C1 171 Long 23, 24, 25, 43, 513
forwback 271, 272, 277 Loop 61 – 64
foub 404, 405, 411 LTrim 95, 96
526
Subject Index
M P
MDETERM 224 Password 161
Method Path 161, 163
barrier function 472 PERSONAL.XLSB 184 – 186, 189, 190
bisection 306, 309 Preserve 73, 74
interior point 473 Print 102, 103
of object 151, 152 Private 81, 121
penalty function 466 Procedure
secant 310, 311 built-in 85
Steffensen 370 Fourier Analysis 396
tangent 366 user-defined
trapezoidal 384 function 77
variable replacement 462 subroutine 79
Mid 97, 98 Property of object 151, 152
mini 432, 435, 436, 439, 442 Public 81
minim 447, 453, 464, 486 Public Const 82
MINVERSE 224
MkDir 103 – 105 Q
MMULT 224 QBColor 169
Mod 39, 40, 42, 56 Quit 158, 165
mos 288, 289, 294
MsgBox 85 – 88, 98 R
Randomize 76, 476, 478
N Range 148, 152 – 154, 171, 172, 178
Name 120, 161, 162, 167, 169 ReDim 71, 73 – 75, 142, 210
Next 58 – 60, 172 ReferenceStyle 148
Not 48 – 50, 82 Replace 97
Now 25, 26, 47, 100, 153, 159, 476 Reset 20
NumberFormat 148, 245 Right 97, 98
RmDir 106
O Rnd 46, 75, 76, 476, 478
Object 151, 166, 514 Rosenbrock 425
Offset 172, 174 Round 45, 46, 51, 300
OnTime 159, 160 Rows 142, 172, 173, 188, 189
Open 101, 103 RTrim 95, 96
Operator Run 19
case 56 Run To Cursor 19
conditional 53
conditional jump 54 S
unconditional jump 52 Save 161, 162
Option Base 69 SaveAs 161, 164
Option Explicit 24 Select 148, 153, 172, 174, 178, 328
Optional 82, 83, 230 Select Case 56, 57
Or 48 – 51, 112 Selection 148, 173, 174, 181, 328
Output 101 – 103 Set 152, 164, 170, 174, 182, 328
527
Subject Index
T W
table 315, 316, 318, 324 Wend 61
Tan 517 While 61 – 63
Text 121, 123, 125 Width 117
TextAlign 120 With 91 – 93, 156 – 158
TextBox 120 – 122, 125, 151 Workbook 161, 164
Then 53 – 55, 188, 403 Workbooks 152, 161, 162, 164
Time 25, 26, 47, 100, 159 Worksheet 167 – 170
TimeValue 99, 100, 159, 476 Worksheets 152 – 155, 167 – 170
To 58 – 60, 68, 71
Toggle Breakpoint 19 X
TRANSPOSE 141, 142, 224, 295 xlCalculationAutomatic 156
TRANSPOSEA 142, 143, 224 xlCalculationManual 156, 159
Trim 95, 96 XLSTART 186