Chi M. Phan - Numerical Calculations For Process Engineering Using Excel VBA-CRC Press (2023)
Chi M. Phan - Numerical Calculations For Process Engineering Using Excel VBA-CRC Press (2023)
Numerical Calculations for Process Engineering Using Excel VBA provides numeri
cal treatment of process engineering problems with VBA programming and Excel
spreadsheets. The problems are solving material and energy balances, optimising
reactors and modelling multiple-factor processes. The book includes both basic and
advanced codes for numerical calculations. The basic methods are presented in dif
ferent variations tailored to particular applications. Some macros are combined with
each other to solve engineering problems. Examples include combining the bisection
method and binary search to optimise an implicit correlation, combining golden sec
tion search with Euler’s method to optimise a reactor and combining bisection code
and Euler’s method to solve steady-state heat distribution. The text also includes non-
conventional examples such as harmony search and network analysis. The examples
include solutions to common engineering problems such as adiabatic flame tempera
ture, plug flow reactor conversion, batch reactor, heat diffusion and pinch analysis of
heat exchanger networks. The VBA code is presented with mathematical equations
and flowcharts, enabling the audience to adopt the solutions to different problems.
The book contains many demonstrations of numerical techniques to guide users. It
also includes useful summaries of VBA commands/functions and Excel-predefined
functions accessible in VBA.
While the book is developed primarily for undergraduate students, the book is a
helpful resource for postgraduate students and engineers.
Numerical Calculations for
Process Engineering Using
Excel VBA
Chi M. Phan
Designed cover image: © Shutterstock
First edition published 2024
by CRC Press
2385 NW Executive Center Drive, Suite 320, Boca Raton FL 33431
and by CRC Press
4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN
CRC Press is an imprint of Taylor & Francis Group, LLC
© 2024 Chi M. Phan
Reasonable efforts have been made to publish reliable data and information, but
the author and publisher cannot assume responsibility for the validity of all
materials or the consequences of their use. The authors and publishers have
attempted to trace the copyright holders of all material reproduced in this
publication and apologize to copyright holders if permission to publish in this form
has not been obtained. If any copyright material has not been acknowledged please
write and let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be
reprinted, reproduced, transmitted, or utilized in any form by any electronic,
mechanical, or other means, now known or hereafter invented, including
photocopying, microfilming, and recording, or in any information storage or
retrieval system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, access
www.copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222
Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are not
available on CCC please contact [email protected]
Trademark notice: Product or corporate names may be trademarks or registered
trademarks and are used only for identification and explanation without intent to
infringe.
ISBN: 978-1-032-42828-4 (hbk)
ISBN: 978-1-032-42829-1 (pbk)
ISBN: 978-1-003-36451-1 (ebk)
DOI: 10.1201/9781003364511
Typeset in Times
by Apex CoVantage, LLC
Contents
Preface.......................................................................................................................ix
About the Author ......................................................................................................xi
v
vi Contents
Appendices������������������������������������������������������������������������������������������������������������ 133
List of Useful VBA Functions Which Returns a Numerical Value... 133
Other Useful VBA Functions ........................................................... 133
List of Useful Worksheet Functions (Using the
WorkSheetFunction Object in VBA)................................................ 134
ix
About the Author
Chi M� Phan (PhD, BEng) has taught in the Department of
Chemical Engineering at Curtin University for over 15 years.
He has taught classes in process analysis, process calculations,
process modelling and simulations. In addition to Curtin Uni
versity, he taught at the University of Newcastle (Australia) and
the University of Hyogo (Japan). He has developed many nu
merical models for his research in surface science.
xi
1 Introduction to Excel and
VBA
1.1 MICROSOFT EXCEL
Microsoft Excel is a spreadsheet program written and distributed by Microsoft for com
puters. It features an intuitive interface and capable calculation and graphing tools, which
have made Excel one of the most popular microcomputer applications. It is overwhelm
ingly the dominant spreadsheet application available. All Microsoft Office versions
(including Apple Mac OS versions) currently have Excel with Visual Basic applications.
DOI: 10.1201/9781003364511-1 1
2 Calculations for Process Engineering Using Excel VBA
be created by recording. Macro recording can produce VBA code replicating user
actions, thus allowing simple automation of regular tasks. However, writing, editing
and debugging macros in the VBA editor is more effective for numerical calcula
tions. This editor screen can be accessed by hitting the keystroke Alt + F11.
By default, new Excel workbooks have no module. The users must insert the mod
ules. Once inserted, the module can be renamed. All macros in different modules of
the same Excel workbook can be used in any spreadsheet.
VBA implements Microsoft’s Visual Basic, built into all Microsoft Office appli
cations (including Apple Mac OS versions). VBA is closely related to Visual Basic
but can only run code from within a host application rather than as a stand-alone
application. As a result, VBA can be used to control one application from another
application (for example, automatically creating a Word report from Excel data).
Application.Workbooks(“Book1.xls”).Worksheets(“Sheet1”).
Range(“A1”)
If you omit specific references, Excel uses the active objects. For example, if
Book1 and Sheet1 are active, then the preceding reference can be simplified to:
Range(“A1”)
Objects have properties. For example, a Range object has such properties as Value
and Address. A Chart object has such properties as Title and Type. You can use VBA
to determine object properties and to change properties.
The user can refer to a property of an object by combining the object name with
the property name, separated by a period. For example, you can refer to the value in
cell A1 on Sheet1 by
Worksheets(“Sheet1”).Range(“A1”).Value
Introduction to Excel and VBA 3
You can assign values to variables. A variable is a named element that stores data.
You can use variables to store such things as values, text or property settings. To as
sign the value in cell A1 on Sheet1 to a variable called X_value, use the following
statement:
X _ value = Worksheets(“Sheet1”).Range(“A1”).Value
Worksheets(“Sheet1”).Range(“A1”).ClearContents
While VBA code can manipulate the cells in an Excel spreadsheet directly,
it is not always used in numerical calculations. Instead, a macro is often used
for the purpose. The purpose and limitations of macros are explained in the next
section.
VBA subs are more useful for “action” procedures (e.g. formatting cells, displac
ing value in Message Box). To use a sub to export results to an Excel spreadsheet,
a set value can be used. However, the range of cells is specified within the sub and
cannot be moved as with functions. One effective way to use the sub in an Excel
spreadsheet is to create a shape and assign a sub to it. Then the user can click on
the shape. Alternatively, the sub can be assigned to a particular keystroke. Using the
Excel menu and keyboard commands, subs can be created by recording. However,
the recorded macros cannot incorporate logic, branching and looping.
To use double3 or double4 in Code 1.2, one can create a Command Button in an
Excel spreadsheet and then assign the subroutine to it (Figure 1.2). Subsequently, the
user needs to click on the message box to close it. The subroutines do not take the
input value as an argument. In contrast, functions allow both (i) a numerical value as
an argument and (ii) the value stored in a specific cell as the argument.
The output from the subroutine cannot be used by other VBA functions or subrou
tines. This disadvantage of subroutines limits their usage in numerical calculations.
As seen, both subs and functions can do the same calculations. The two essential
function features are the return of a value (or a set of values) and multiple uses in the
spreadsheet. Once created, functions are available in the Excel library. VBA func
tions work in the same way as formulas and built-in functions in Excel. A function
Introduction to Excel and VBA 5
can be used multiple times within the same Excel workbook. Users can create cus
tom functions for any action and then access the functions from a cell or a direct
reference from a cell. In addition, the function return value can be combined with
another sub/function. For this reason, VBA functions are more convenient for numer
ical calculations and will be used mainly in this book.
Dim x As Integer
Dim y1,y2 as string
Dim A(2,10) as long
Dim B() As double
If omitted, the default type of variable is Variant, which means the variable can
be any value (text, numbers, dates, time or objects). For numerical types of variables,
VBA has predefined ranges of values (as in Table 1.1). Therefore, it is important to
6 Calculations for Process Engineering Using Excel VBA
TABLE 1.1
Range of Values for Numerical Data Types
Data Type Range of Values
Byte 0 to 255
Integer –2,147,483,648 to 2,147,483,647
Short –32,768 through 32,767 (short integer)
Long –9,223,372,036,854,775,808 through 9,223,372,036,854,775,807 (long integer)
Single –3.402823×1038 to –1.401298 ×10–45 for negative values, 1.401298×10–45 to
3.402823×1038 for positive values
Double –1.79769313486232×10308 to –4.94065645841247×10–324 for negative values,
4.94065645841247 ×10–324 to 1.79769313486232 ×10308 for positive values
Decimal +/–79,228,162,514,264,337,593,543,950,335 for no decimal points, +/–7.922816
2514264337593543950335 for 28 places to the right of the decimal
consider the expected range of the value. If any calculated value within the code is
outside the defined range, the VBA code will give an error (#VALUE) without spec
ifying the problem.
The ranges might change with the Excel version. The specified values can be
checked in detail on the Microsoft website.
https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/data
types/
Code 1�3� Size of a matrix (since the function name is Variant, the code
can return a text string or a numerical value)�
Function SM(A)
‘return the size of the matrix
Dim N as integer
N = A.Rows.Count
If A.Columns.Count <> N Then
SM = “Not a square matrix”:
Else
SM = N
End If
End Function
Array variables can be either static or dynamic. A dynamic array is an array that
can be resized, as opposed to a static array, which cannot be resized. For static array,
the size is fixed at declaration, with the statement Dim. Dynamic data can be reini
tiated by the statement Redim. An existing array can be extended while keeping the
existing value using the ReDim Preserve statement.
ReDim can be used to redefine the variable type as well. However, it would
create confusion for code users. More often, ReDim is used to redefine the dimen
sion of an array or matrix. It is constructive for output with a variable number of
answers.
The values of an array can also be reset with Erase instead of using Redim. While
Redim resizes the dimension of the array, the Erase statement reinitialises the ele
ments of fixed-size arrays and releases dynamic-array storage space. The initialisa
tion depends on the type of variables. For example, Erase resets the fixed numeric
array to zero and the fixed variant to Empty.
The previous presents three functions of the array. Using function mymatrix(5) in
the latest Excel version will return a 5 × 10 table of zero. Typing mymatrix2(5) will
return the #VALUE (VBA cannot express a three-dimensional matrix in an Excel
spreadsheet). Typing mymatrix5(5) will return a single value of zero. If the VBA
function returns a two-dimensional matrix, another VBA function can use that output.
9
23 cesium barium lutetium hafnium tantalum tungsten rhenium osmium iridium platinum gold mercury thallium lead bismuth
24 132.9 137.3 175.0 178.5 180.9 183.8 186.2 190.2 192.2 195.1 197.0 200.6 204.4 207.2 209.0
10 Calculations for Process Engineering Using Excel VBA
within the Excel workbook. The code can be used in other Excel work in the same
folder by using the following:
Workbooks(“example1–1.xlsm”). Worksheets(“PeriodicTable”). Range(“C1:BP46”)
Code 1�5� Example of For Each Next loops to calculate the molecular
weight�
Function MW(name)
Dim Cell As Range
MW = “Element name is not found”
For Each Cell In Worksheets(“PeriodicTable”).
Range(“C1:BP46”)
If StrComp(name, Cell.Value) = 0 Then
MW = Cell.Offset(2, 0). Value ‘MW is stored
2 cells below the Symbol
End If
Next Cell
End Function
The For Next loop follows a sequence of numbers (the data is in Table 1.2). The
default step (1) is used if the step is omitted. Alternatively, any integer (including
negative values) can be used. The For Next loop is more useful for numerical calcu
lations and will be used frequently in this book.
TABLE 1.3
Different Do Loop Formats
Loop format Description Example
Do While . . . Loop Runs 0 or more times while the Do While “condition is met”
condition is true Loop
Do . . . Loop While Runs 1 or more times while the Do . . .
condition is true Loop While “condition is met”
Do Until . . . Loop Runs 0 or more times until the Do Until “condition is met”
condition is true Loop
Do . . . Loop Until Runs 1 or more times until the Do . . .
condition is true Loop Until “condition is met”
While . . . Wend Same as Do While . . . loop
Introduction to Excel and VBA 11
Code 1.5 shows two loop structures that are used to find the smallest number in the
Fibonacci series which is larger than x.
A common problem with the loop is the requirement for initial conditions. For
example, the numerical method requires code to repeat the iterations, so the calcu
lated error is smaller than 0.01. The calculated error is updated within the loop. One
can use the condition as “calculated_error > 0.01” with structure 1 or 2. Alterna
tively, one can use “calculated_error < 0.01” and structure 3 or 4. Either way, the
initial value of calculated_error must be initialised before the loop.
Range(“A2”).Value=1
Cells(2,1).Value =1
It should be noted that the first index in Cells is the row number, and the column
number is the second index (1 corresponds to column A). For example, Cells(10,2)
corresponds to B10, and Cells(2,10) corresponds to cell J2. To get the value from cell
A2 of the active spreadsheet, one can use the following:
x = Range(“A2”).Value
x = Cells(2,1).Value
The command is useful for selecting values as inputs for a numerical procedure.
Alternatively, one includes the cells as arguments for the function.
Introduction to Excel and VBA 13
Code 1�7� Calculate the average value of three numbers stored in cells
A1, A2 and A3, and export the value to cell B1�
Sub ave _ 3()
Dim ave
ave = (Range(“a1”).Value + Range(“a2”).Value +
Range(“a3”).Value) / 3
Range(“B1”).Value = ave
End Sub
Please note that the function ave_4 does not work by being directly called from
an Excel spreadsheet, that is, using it as a user-defined function. The reason is how
Excel handles VBA functions. When Excel uses a user-defined function, the function
can only access the ranges handed to it via parameters. Any access to other ranges
will result in a circular reference and potential cancellation of the execution. How
ever, if a function is called within a subroutine, Excel does not mind. Hence, using
sub ave_5 in combination with function ave_4 will generate the same result as sub
ave_3.
values. In addition, Excel and VBA have an extended list of text-related functions
not included in this book.
1.2.8.1 Pi()
Excel has the function Pi(), which returns the value of Pi accurately to 15 digits. The
function can be called in VBA.
Dim pi
pi = WorksheetFunction.pi()
TABLE 1.4
Errors When Using VBA Functions in Excel Spreadsheets
Error Meaning
#NAME? This error is displayed when Excel does not recognise text in a formula. For example, the
name of a function may need to be spelled correctly.
#N/A Excel displays this error when a value is unavailable to a function or formula.
#NULL! A space was used in formulas referencing multiple ranges; a comma separates range
references.
#NUM! A formula has invalid numeric data for the type of operation (including VBA functions).
#REF! A reference is invalid.
#VALUE! The wrong type of operation or function argument is used.
16 Calculations for Process Engineering Using Excel VBA
1.3.4 Breakpoints
The breakpoint specifies the line in your code where VBA should pause the execu
tion of the macro operation when debugging the code. The shortcut key for adding
a breakpoint is F9. Create a breakpoint, position the cursor on the specific line of
your code where you want VBA to pause and press F9. Alternatively, locate the
line of code where you want to add the breakpoint and click in the left grey margin
beside the line. A dark red dot will appear on the margin beside the specified line to
indicate that the breakpoint has been created. The specified line of code will also be
highlighted with the same colour (Figure 1.4).
To remove the breakpoint, click on the dot again or press F9 with the cursor posi
tioned in the highlighted line of code. If there are many breakpoints, the user can
remove them simultaneously by pressing Ctrl+Shift+F9.
Once the code runs to a breakpoint, VBA stops and highlights the breakpoint in
yellow. Then the user can continue the code by pressing F5. Figure 1.4 shows the
immediate values of the loop by inserting “Debug�Print i,f2” in function LFn_4
(Code 1.10).
Solver has three algorithms. While the tools are practical in many cases, they do
not show the underlying calculations. Thus, Solver and Goal Seek are not covered
in this book.
2 Roots of an Equation
2.1 INTRODUCTION
Solving an equation is the most basic mathematical challenge. This chapter presents
some methods to solve an equation, their shortcomings, and their advantages. More
importantly, numerical methods often require solving a pre-arranged equation and
then using the output for further operation. Consequently, the methods are presented
in VBA forms, which can be routinely employed with other methods to solve com
plicated problems in subsequent chapters.
x1 + x2
x3 = Eq. 2.1
2
Depending on the value of f(x3), a new interval is selected, either (x1,x3) or (x3,x2).
The halving procedure is repeated until the desired accuracy is met. The application
will depend on the nature of the problem. In this chapter, the method is presented
with flowcharts and codes. The methods can be combined with other functions to
solve complicated problems. For example, the combined shooting/bisection method
is used for heat transfer—the combined bisection/tear analysis for solving material
balance with a recycling stream.
For coding, there are many variations of the method. Here a simple example is
used to demonstrate these variations.
20 DOI: 10.1201/9781003364511-2
Roots of an Equation 21
Solution
The halving procedure can be applied with three options in each iteration.
There are some important notes on the VBA function in Code 2.1. First, the
function is evaluated within one line to be typed directly. However, the func
tion evaluation can be set as a separate VBA function and called in this function
several times. Such an arrangement can help to reduce typos. Furthermore, the
separate function can be called in an Excel spreadsheet directly and checked if the
selected interval (a,b) contains a change-of-sign. Sometimes function evaluation
requires multiple calculation steps and cannot be typed within one line. Hence,
it is advised to set the equation as a separate VBA function, as in the following
example.
The second noteworthy comment is about the first option in the If . . . Elseif struc
ture, f ( x ) = 0 . This option may help to reduce the number of iterations/calculations,
22 Calculations for Process Engineering Using Excel VBA
but it rarely happens. If there are only two options, the code will be much simpler.
Finally, the usage of SkipPoint: (or Exit Loop) is not recommended. Thus, the option
f ( x ) = 0 should be removed in most cases.
x1 x2
n= Eq. 2.3
tolx
Hence, the For � � � Next structure can be used. The problem is solved, with the
required error, tolx, being an argument, using the code to find a solution between
(0.5, 2) with an error of 0.0001.
As the function is separated from the bisection function instead of using the
direct formula as in Code 2.1. The previous format will be more useful for
other cases. Notably, within each iteration, this VBA code requires two function
evaluations, f1(Lo) and f1(Mi). The extra evaluations can be inefficient when
the function evaluation is computationally intensive (see examples in the next
chapter).
Roots of an Equation 23
1 æ e / Dh 2.51 ö
= 2log10 ç + ÷ Eq. 2.4
ç ÷
f è 3.7 Re f ø
where:
f is the Darcy friction factor, ε (m) is roughness height, Dh (m) is the inside
diameter of the pipe and Re is the Reynolds number.
Part A� Calculate f with a required error less than 0.001 for the following condi
tions: e = 0.001 m, Dh = 0.05 m and Re = 4000 . The initial range is between
0.001 and 1.
Part B� Calculate f when the required difference between the left-hand and
right-hand sides of the equation is less than 0.001.
Solution
For part A, the error is specified for the friction factor, f. Hence, the initial values can
determine the number of iterations, and a For . . . Next loop structure (Figure 2.1)
can be used. The While . . . Wend loop structure (Figure 2.2) can also be used, with
the condition of err > tolx.
FIGURE 2.1 Flowchart for bisection code with a For . . . Next loop.
24 Calculations for Process Engineering Using Excel VBA
FIGURE 2.2 Flowchart for bisection code with a While . . . Wend loop.
Code 2�3� Bisection code with a For � � � Next loop and a single function
evaluation�
Function BisectionX(Lower, Upper, e, D, Re)
Dim k, n, M, err, tol, c1, c2, c3
tol = 0.001
n = (Upper–Lower)/tol
c1 = colebrook(Lower, e, D, Re)
For k = 1 To n
M = (Lower + Upper) / 2: c3 = colebrook(M, e, D, Re)
If c1 * c3 < 0 Then
Upper = M
Else
Lower = M:c1=c3
End If
Next k
BisectionX = M
End Function
Function colebrook(f, e, D, Re)
colebrook = (1 / f ^ 0.5) + 2 * Log((e/(D * 3.7)) +
(2.51 / (Re * (f ^ 0.5)))/Log(10))
End Function
Roots of an Equation 25
The previous bisection code has removed the f(x3) = 0 option. Furthermore, the calcula
tion steps are rearranged so that each iteration requires only one function evaluation, c3=
f(x3). It should be noted that the initial values have to be selected so that there is a change
of sign. As a result, evaluation of c2 is not required. However, a validation of sign change
(such as in Code 2.1) might be needed in the general case. For parameter values, Code
2.3 returns f = 0.010743043. While the answer is sufficiently good, there is no guarantee
that the difference between the left and right sides of Eq. 2.4 is smaller than 10–4.
Code 2�4� Bisection code with limitation in function value, using the
same objective function in Code 2�3�
Function BisectionF(Lower, Upper, e, D, Re) ‘return f
Dim M, tol, c1, c2, c3, k
tol = 10 ^ -5
M = (Lower + Upper) / 2
c1 = colebrook(Lower, e, D, Re)
c3 = colebrook(M, e, D, Re)
k = 0
While Abs(c3) > tol And k < 100
If c1 * c3 < 0 Then
Upper = M
Else
Lower = M: c1=c3
End If
M = (Lower + Upper) / 2: c3 = colebrook(M, e, D, Re)
k = k + 1
Wend
BisectionF = M
End Function
Part B� To achieve the required accuracy, the error in function colebrook is used as the
termination condition, as in Code 2.4. In this case, the number of iterations will depend
on the specific tolerance of the function; thus, the number of iterations is unknown.
Consequently, the For . . . Next loop is not suitable. Code 2.4 uses the While . . . Wend
structure of Figure 2.2, with a small variation in testing conditions. The method can be
applied to part A as well (by replacing Abs(c3) with Abs(Upper-Lower)).
of sign. Since the scanning procedure requires function evaluations, the last interval
from the scanning step can be used as the starting region for the bisection method.
The previous code can be applied with all the parameters in Example 2.1, with a
starting point of 0.001. After the scanning part, the code will find a suitable interval
between 0.0085 and 0.0165 after four scanning steps. In the case of multiple solu
tions, scanning can target the solution.
1
f ( x) = Eq. 2.5
x
Roots of an Equation 27
f ( x ) = x2 Eq. 2.6
This equation has a root x = 0, but both sides of the root are positive. There is
an effective way to overcome these failures. In these cases, one can try to minimise
the square of f(x) within a specific range. A minimum of zero will indicate a root,
whereas a non-zero minimum indicates no feasible root. To find a minimum of f 2(x),
one of the optimisation methods in Chapter 4 can be used.
f ( xi )
xi +1 = xi Eq. 2.7
f ’( xi )
f ( xi ) f ( xi 1 )
f ’( xi ) = Eq. 2.8
xi xi 1
( xi xi 1 )
xi +1 = xi f ( xi ) Eq. 2.9
f ( xi ) f ( xi 1 )
The previous method is named the Secant method (Chapra and Canale 2010).
While this method requires two values to calculate the following value (Figure 2.3),
these two values should be close to each other (to avoid fluctuation and divergence).
The termination condition can be based on the error in x or f. The solution will de
pend on the initial point and step size selection.
28 Calculations for Process Engineering Using Excel VBA
A VBA function of the secant method is presented in Code 2.6., which is applied
to the same Colebrook equation.
Using the code with x1 = 0.001, x2 = 0.002 and tol = 10–7, one can get the same
answer after eight iterations. It should be noted that the answer is extremely sensi
tive to the initial guesses. A bad selection, for example, 0.001 and 0.1, may lead to
a negative value of x3 and return #VALUE! (since the Colebrook function valuates
log(x) and x0.5).
The Regula Falsi method can be considered a mix between the bisection and secant
methods. The method starts with a change-of-sign interval, as with the bisection
method. Subsequently, the dividing point is selected by linear regression between the
two points (Figure 2.3) instead of the mid-point. The iterative formula is:
f ( x1 )
x3 = x1 + ( x1 x2 ) Eq. 2.10
f ( x1 ) f ( x2 )
By comparing the signs of the f(x3), the next interval can be either (x3,x1) or (x2,x3).
The linear regression formula can solve the friction factor problem. The method can
not be used with the For . . . Next loop because the number of iterations cannot be
determined in advance.
Answer
Insert this line (after the loop).
Debug.Print k
Answer
Change the function name to PF_2 and insert the following lines after the loop:
Dim output(1 To 2, 1 To 2)
output(1, 1) = “solution”: output(2, 1) = M
output(1, 2) = “# iters”: output(2, 2) = k
PF _ 2 = output
Also, do the same for the bisection method. The modified code will produce the
number of iterations. Using the same initial range (0.001, 1) and the required error,
10–7, the bisection method requires 30 iterations, while the Regula Falsi method re
quires 93 iterations. In this particular instance, the bisection method is three times
faster. However, if the range is changed to (0.01, 1), the respective iterations are 27
and 7, which means the Regula Falsi method is about three times faster. The change
in efficiency is due to the non-linear nature of the Colebrook function within this
range. The Colebrook function for different values of f can also be calculated and
plotted to demonstrate the correlation between f and the VBA function graphically.
3 Applications of Roots
of an Equation
3.1 INTRODUCTION
The previous chapter demonstrates some numerical methods to solve a single explicit
equation. This chapter presents some applications of the methods to engineering
problems. In these problems, the nature of the correlation/data input is more compli
cated than an explicit equation. Therefore, the VBA code in the previous chapter is
modified to adapt to these problems.
CH 4 + 2O2 ® CO2 + 2H 2 O
Both fuel and air enter the reactor at 25°C. Heat capacity equations (Cp in kJ/
gmol/°C and T in °C) for gases are determined from the following equation:
Cp = a + b ´ T + c ´ T 2 + d ´ T 3 Eq. 3.1
The heat capacity constants and heat of formation are given in Table 3.1. Assume
complete combustion and air containing 21% oxygen and 79% nitrogen.
Part A� Determine the adiabatic flame temperature of methane combustion
with air; the air is supplied 50% excess.
Part B� Determine the required excess air so the adiabatic flame temperature
is 1500°C.
DOI: 10.1201/9781003364511-3 31
32 Calculations for Process Engineering Using Excel VBA
TABLE 3.1
Heat Capacity Constants and Heat of Formation under Standard Conditions
(Himmelblau and Riggs 2012)
A B C D E F
1 Heat of formation Heat capacity constants
2 a b c d
3 CH4 –49.963
4 CO2 –393.25 36.110 4.233E-02 –2.887E-05 7.464E-09
5 H2O –241.835 33.460 6.880E-03 7.604E-06 3.593E-09
6 O2 0 29.100 1.158E-02 –6.076E-06 1.311E-09
7 N2 0 29.000 2.199E-03 5.723E-06 –2.787E-09
Solution
Part A� For complete combustion, all fuel CH4 reacts and forms CO2. Using the basis
of 1 gmol of CH4, the amount of the gases is easily calculated. It should be noted
that water is formed in vapour form. Following the material balances, the quantities
of the gas output are:
xCO2 = 1 gmol
xH2O = 2 gmol
xO2 = 2x gmol
xN2 = 2 × (79 / 21) × (1 + x) gmol
In this system, x is the percentage of excess air. For part A, x equals 0.5. The heat
of the reaction is calculated from the heat of formation:
J
°
DHrxn = DHˆ °f ( CO2 ) + 2DHˆ °f ( H 2 O ) DHˆ °f ( CH 4 ) = 826957 Eq. 3.2
mol
Consequently, the adiabatic flame temperature Td is satisfied by the following
equation:
å xi Cpi ( T ) dT =826957
Td
ò25
Eq. 3.3
Part B� The BisectionT function in Code 3.1 can determine Td at a given excess,
but the question requests the reverse correlation. Hence, another code can be com
bined with the previous VBA function. Code 3.2 (in combination with Code 3.1) pro
duces x = 0.531. The combination takes a significant time if the limits are far apart.
It should be noted that this problem can be solved analytically by material bal
ances. However, the calculation process is tedious with many constants. Writing two
short VBA functions is more efficient (as we already have the VBA functions in Code
3.1). In this case, all VBA functions must be in the same Excel file. For example,
34 Calculations for Process Engineering Using Excel VBA
the Excel spreadsheet needs to have heat capacity constants, as in Table 3.1. Using
multiple VBA functions in this fashion is necessary for many complicated numeri
cal problems. In this instance, the code used bisection on another bisection method.
Since both functions require multiple iterations, an appropriate selection of initial
values can significantly reduce the calculation time.
C2 H 4 + HCl ® C2 H 5 Cl
Applications of Roots of an Equation 35
The process can be simplified in the following diagram, adapted from exam
ple 10.2–3 (Felder and Rousseau 2005). The fresh feed contains 50 kgmol/h
of HCl and C2H4 each (equal molar flow). The fresh feed is mixed with the
recycle stream before entering the reactor. The single-pass ethylene conver
sion is 90%. After the reactor, the stream is separated into Product (containing
C2H5Cl only) and Stream S-4 (containing C2H4 and HCl). Stream S4 is split
into Waste and Recycle streams. Streams S4, Waste and Recycle have the same
composition.
Find the molar flow for the recycle stream if the waste stream has a flow
rate of 8 kgmol/h.
Solution
First, a mathematical model is developed to describe all material balances of the
process. Generally, each stream will have three chemicals (HCl, C2H4 and C2H5Cl).
Since the flow rates of HCl and C2H4 are always equal on all streams, the unknown
variables can be reduced to 1 and thus become a single-variable function. For other
cases, the tear analysis may produce a multiple-dimensional system (see Example
8.2) and require a multiple-dimensional method.
The modelling of this process is based on a tear analysis. Tear analysis is per
formed by identifying recycle or loop streams in the process flow diagram and tem
porarily “tearing” them to create separate input and output streams. This simplifies
the system into smaller sub-processes, allowing for more straightforward calculation
and simulation. Once the steady-state conditions of these smaller sub-processes have
been determined, the torn streams are reconnected.
For this particular problem, the tear stream can be either S1, S2, S4 or the recycle
stream. For convenience, the recycle stream is selected. Hence, the flow rate of the
recycle stream is assigned a random value, Rg. From Rg, the component flow rates
in recycle stream are calculated. Subsequently, the materials of other streams are
calculated from streams S1 to S2 to S4 (Figure 3.1). Consequently, the other side
of the tear is calculated from S4, resulting in a value of Rcal. The next step of tear
analysis is to adjust Rg so that Rcal = Rg. This can be done by a VBA function, as in
Codes 3.3 and 3.4.
Code 3�3� Calculate the difference between the guessed and calculated
tear steam value (one variable)�
Function diffR(Rg, feed, Conv, W)
Dim S1(3), S2(3), S4(3), Pro(3), Waste(3), R(3)
Dim Rcal
R(1) = Rg / 2: R(2) = Rg / 2 ‘calculate component of R
S1(1) = feed / 2 + R(1): S1(2) = feed / 2 + R(2)
S2(1) = S1(1) * (1–Conv): S2(2) = S1(2) * (1–Conv):
S2(3) = S1(1) * Conv ‘we don’t need S(3) for calc
S4(1) = S2(1): S4(2) = S2(2)
R(1) = S4(1)–W / 2: R(2) = S4(2)–W / 2:
Rcal = R(1) + R(2)
diffR = Rg–Rcal
End Function
The function in Code 3.3. calculates the difference between Rg and Rcal. In this
code, the component flow rates of each stream are presented by an array of two
elements. The flow rates are calculated from each unit operation’s material balance.
Else
BisectionR = “Wrong initial estimates”
End If
End Function
By applying this code, the flow rate of the recycle stream is determined at R = 2.22
mol/h.
Btu
Û t = 322.9 Eq. 3.4
lb
ft 3
Vt = 6.25 Eq. 3.5
lb
The steam and vapour saturated values are given in Table 3.2.
Determine the composition (vapour fraction) and temperature of the mixture.
Solution
The unknowns of the process are vapour fraction xv, total pressure P and temperature
T. The degree of freedom of the system is zero. There is a unique solution, a specific
combination of xv, P and T, to satisfy the two conditions in Eqs. 3.4 and 3.5. On the
other hand, the data are available in standard steam tables. In such tables, U and H are
given for both phases as functions of T (or P). An example of a steam table is given
in Table 3.2, which can be stored in an Excel spreadsheet.
38 Calculations for Process Engineering Using Excel VBA
TABLE 3.2
Steam Table for Saturated Vapour
Temperature Sat Pressure Specific Volume (ft3/lbm) Internal energy (Btu/lbm)
(F) (lb/in2) Sat. Liquid Sat. Vapour Sat. Liquid Sat. Vapour
32.018 0.08871 0.01602 3299.9 0 1021
35 0.09998 0.01602 2945.7 3.004 1019
40 0.12173 0.01602 2443.6 8.032 1015.6
45 0.14756 0.01602 2035.8 13.05 1012.2
50 0.17812 0.01602 1703.1 18.07 1008.9
55 0.21413 0.01603 1430.4 23.07 1005.5
60 0.25638 0.01604 1206.1 28.08 1002.1
65 0.30578 0.01604 1020.8 33.08 998.76
70 0.36334 0.01605 867.18 38.08 995.39
75 0.43016 0.01606 739.27 43.07 992.02
80 0.50745 0.01607 632.41 48.06 988.65
85 0.59659 0.01609 542.8 53.06 985.28
90 0.69904 0.0161 467.4 58.05 981.9
95 0.81643 0.01612 403.74 63.04 978.52
100 0.95052 0.01613 349.83 68.03 975.14
110 1.2767 0.01617 264.96 78.01 968.36
120 1.6951 0.0162 202.94 88 961.56
130 2.226 0.01625 157.09 97.99 954.73
140 2.8931 0.01629 122.81 107.98 947.87
150 3.7234 0.01634 96.929 117.98 940.98
160 4.7474 0.01639 77.185 127.98 934.05
170 5.9999 0.01645 61.982 138 927.08
180 7.5197 0.01651 50.172 148.02 920.06
190 9.3497 0.01657 40.92 158.05 912.99
200 11.538 0.01663 33.613 168.1 905.87
210 14.136 0.0167 27.798 178.15 898.68
212 14.709 0.01671 26.782 180.16 897.24
220 17.201 0.01677 23.136 188.22 891.43
230 20.795 0.01684 19.374 198.31 884.1
240 24.985 0.01692 16.316 208.41 876.7
250 29.844 0.017 13.816 218.54 869.21
260 35.447 0.01708 11.76 228.68 861.62
270 41.877 0.01717 10.059 238.85 853.94
280 49.222 0.01726 8.6439 249.04 846.16
290 57.573 0.01735 7.4607 259.26 838.27
300 67.028 0.01745 6.4663 269.51 830.25
Applications of Roots of an Equation 39
The four values (Ul, Uv, Vv, Vl) are determined by linear interpolation from the
table. The solution is based on the principle of the bisection method using two VBA
functions. In the first function, the temperature is an input, and the corresponding
total volume is the output. The function includes three steps:
1 For a given value of T, the corresponding Uv, Ul, Vv, Vl are obtained by
interpolating data.
2 xv is calculated by an interpolation formula of Uv, Ul to satisfy Eq. 3.6, U = 322.9
Btu/lbm. Note that if Uv < Ut or Ul >Ut, there is no physically feasible value of
xv. However, the formula can assign xv = 0 and xv = 1 under those conditions.
3 The total volume Vt is calculated by Eq. 3.7 from xv and Vv,Vl.
A bisection (or false-position method) is then applied to find T so that the previous
function, function Tx in Code 3.5, equals Vt. Finally, the determined Tx is combined
with another interpolation to find P.
Code 3�5� Calculating steam temperature and vapour fraction� The discrete
data (steam table) are stored in cells A2:F100 of the active spreadsheet�
Function Tx(t, U)
Dim Ul, Uv, i, fraction, volume, output(1, 1)
output(0, 0) = “total V”: output(0, 1) = “Vapour fraction”
For i = 3 To 200
If t <= Cells(i + 1, 1) And t >= Cells(i, 1) Then
Ul = Cells(i, 5) + (t–Cells(i, 1))/(Cells(i + 1, 1)–
Cells(i, 1)) * (Cells(i + 1, 5)–Cells(i, 5))
Uv = Cells(i, 6) + (t–Cells(i, 1))/(Cells(i + 1, 1)–
Cells(i, 1)) * (Cells(i + 1, 6)–Cells(i, 6))
Select Case U
Case Is < Ul
fraction = 0
Case Is > Uv
fraction = 1
Case Else
fraction = (U–Ul)/(Uv–Ul)
End Select
output(1, 0) = Cells(i, 4) * fraction + Cells(i, 3) *
(1–fraction)
output(1, 1) = fraction:
40 Calculations for Process Engineering Using Excel VBA
Tx = output
Exit Function
End If
Next i
Tx = 2000
End Function
In this case, the vapour and enthalpy are determined via interpolation (instead of
the explicit equations from P or T). Using this code, the solution is T = 210°C and
x = 0.20. It should be noted that the function Tx returns a 2 × 2 matrix. The following
bisection code only requires an element of this output matrix. Since the types of two
variables, entl and ent3, are not specified, the VBA function assigns the whole 2 × 2
matrix to these variables. Subsequently, element (1,0) is used for the bisection proce
dure. The method may not work for an array of other dimensions (see Example 3.6).
Answer
The false-position method needs only one iteration. The reason is that the
Td-versus-x correlation is linear.
Applications of Roots of an Equation 41
Answer
The answers are Td = 206.7°C and xv = 0.21. These are more accurate than the
previous one. The reason is that the linearity of U-versus-T is better than V
versus-T. The solution can be improved using the curve fitting for four values
in Table 3.2.
The first function, Tx, still returns a correct answer (2 × 1 matrix) in an Excel
spreadsheet. The second function returns #VALUE. Maybe other Excel versions can
work with a 1-dimensional array! One way to overcome the error is using output (0,3).
TABLE 3.3
The Refractive Index of the Water-Ethanol Mixture
Ethanol Mole Fraction Refractive Index, nD
0 1.3326
0.101 1.3457
0.2001 1.3535
0.2987 1.3574
0.3332 1.3582
0.4087 1.3595
0.5051 1.3604
0.603 1.3614
0.6664 1.3618
0.7032 1.3617
0.7956 1.3614
0.9075 1.3609
1 1.3593
Hint
Modify the first function in Code 3.5.
4 One-Dimensional
Optimisation
4.1 INTRODUCTION
Finding the optimum, either maximum or minimum, is a common problem in engi
neering. The objective function can be cost, material, energy or time. In compari
son, the input can be any physical variable. This chapter will deal with numerical
optimisation. Analytically, the optimum of an equation can be found to differenti
ate the equation and solve for the root, f’(x) = 0. Various methods in the previous
chapter can find the root of the equation. However, such an approach has two
problems. First, one must clarify whether the optimum is a minimum or a maxi
mum. Second, the differentiation might be challenging or impossible (for example,
implicit equations). The numerical methods in this chapter will overcome those
challenges.
• If f(x1) < f(x2): the region (x2,b) is eliminated; x2 becomes the new b for the
next iteration.
• If f(x1) > f(x2): the region (a,x1) is eliminated; x1 becomes the new a for the
next iteration.
• If f(x1) = f(x2): two regions (a,x1) and (x2,b) are eliminated; x1 and x2 become
new a and b for the next iteration, respectively.
For maximisation, the opposite of conditions (1) and (2) is applied. Option 3 is
sometimes omitted (Figure 4.1). Similar to the bisection method, there are two im
portant shortcomings of the elimination method. First, it does not guarantee that an
optimum exists. Second, it does not guarantee global optimum within the region
DOI: 10.1201/9781003364511-4 43
44 Calculations for Process Engineering Using Excel VBA
(a,b). Generally, a graphic demonstration of the function can be used to verify the
number of optimums between (a,b).
In the literature, there are three ways to select the two interior points: (i) binary
search, (ii) Fibonacci search and (iii) golden section search. In the first search, the
two interior points are selected as close as possible to the midpoint of the region. In
this case, each iteration eliminates nearly half of the original region. While the binary
search is the most efficient way to divide the region, it requires two function evalua
tions at each iteration. For some problems, the function evaluation is a time-consuming
step. Consequently, reducing the number of function evaluations while slightly
increasing the number of iterations is preferable.
The other two methods, Fibonacci and golden section, require only one function
evaluation per iteration (except the first iteration). Even though these two methods
require more iterations than the binary search, they might reduce the computing time.
In these instances, the two dividing points are selected so that one of them would be
the next dividing point of the subsequent iteration. The selection is compensated by
reducing the elimination efficiency and increasing the number of iterations. Fibo
nacci has the lowest number of iterations but requires the series of Fibonacci num
bers. The golden section method relies on the “golden ratio”, which has been studied
since Euclid (Chapra and Canale 2010). While Excel/VBA does not have an in-built
function for the golden ratio, it can be calculated as (1 + 50.5)/2. After each iteration,
the region is reduced by 0.382.
With a predetermined error (the width of the final region), the number of itera
tions of the three methods can be determined. Hence the For Next loop can be used.
Among the three elimination methods, however, the golden section method is the
only one that does not require a predetermined error to calculate the two interior
points (Chapra and Canale 2010). In this section, VBA code for the golden section is
shown. Furthermore, the combination of the golden section method will be demon
strated in Chapter 10.
One-Dimensional Optimisation 45
25
f ( x ) = 400 +1.2x + Eq. 4.1
x
where x is the motor power, expressed in horsepower (h.p.).
The manufacturer can provide a size from 1 to 8 h.p. with an increment of
0.1 h.p. Find the optimum pump size to minimise the cost of operating a pump
and motor.
Solution
In this problem, we need to find a minimum of Eq. 4.1 between 1 and 8. Since the
size must be a multiple of 0.1, the error in x should be 0.1. To get the nearest number
with one digit after the decimal point, the in-built function Round is used.
The code returns an answer of 4.6 after 9 iterations. Without using Round, the
code will return an answer of 4.5569.
x4 =
( 2 2
) ( 2 2
)
1 f1 x2 x3 + f2 x3 x1 + f3 x1 x2 ( 2 2
) Eq. 4.2
2 f1 ( x2 x3 ) + f2 ( x3 x1 ) + f3 ( x1 x2 )
The new point is combined with two of the previous points. Then, either x1 or x3 will
be replaced. The selection is based on the position of x4. Once the three new values
are updated, the iteration can be repeated.
Solution
With x1 = 1, x2 = 2 and x3 = 8, the code returns the same answer after six iterations.
Else
scanning = quadratic(x1 – delx/2, x1, x2, tol)
End If
End Function
The code starts with a small initial value and requires no assumption on the upper
limit. The code also doubles the scanning step after each iteration. The code stops
the scanning procedure when a region containing a minimum, a combination of three
points satisfying the initial conditions of the quadratic interpolation, is found. With
x1 = 0.1 and delx = 0.2 , the code stops scanning after five iterations and starts inter
polating with three values (3.1, 6.3, 12.7).
In the previous example, the VBA function scanning calls the quadratic interpo
lation at the end. A similar approach can be applied to the golden section search and
other region elimination methods. While these methods only require two initial points,
it is essential to know that at least there is an optimum between those two points (that
is, an interior point whose function is smaller than the function values at two ends).
Solution
Part A� Here, the Colebrook function of Example 2.1 is employed again. Since the equation
is in implicit form, a bisection method is needed. However, we want to see the correlation
between f and D. As D increases, velocity and Reynolds number decrease. Consequently,
the value of f changes. A numerical method is needed to find the optimum value of f.
First, fundamental equations of fluid mechanics are needed. For a fluid flow in a
circular pipe (diameter D), the Reynolds number is defined as:
VD
Re = Eq. 4.3
n
One-Dimensional Optimisation 49
4Q
V= Eq. 4.4
p D2
The previous equations can be combined with the Colebrook equation to determine
the friction factor. Bisection code similar to the previous one is used for Part A. How
ever, the inputs include D and Q (instead of D and Re, as in Code 2.5).
Code 4�4� Bisection method to find friction loss as a function of the pipe
diameter�
Function Bisection2(Lower As Double, Upper As Double,
e, D, Q)
Dim M, err, tol, c1, c2, c3, V, Re ‘V and Re are
variables
V = Q * 4 / (D ^ 2 * 3.1416)
Re = D * V / 0.00123
tol = 10 ^ -15
c1 = colebrook(Lower, e, D, Re)
M = (Lower + Upper) / 2: c3 = colebrook(M, e, D, Re)
err = abs(Upper – Lower)
While err > tol
If c1 * c3 = 0 Then
Bisection2 = M
Exit Function
Else
If c1 * c3 < 0 Then
Upper = M
Else
Lower = M: c1 = c3
End If
End If
M = (Lower + Upper) / 2: c3 = colebrook(M, e, D, Re)
err = Upper–Lower
Wend
Bisection2 = M
End Function
The previous code can be applied to values of D from 0.04 to 0.6 and is plotted
in Figure 4.2. The curve indicates that the correlation has a minimum of around
D = 0.2 m .
50 Calculations for Process Engineering Using Excel VBA
Part B� To get the minimum in Figure 4.2, a binary search can be used.
Code 4�5� Combined binary search and bisection methods (the Bisection2
function is in Code 4�4)�
Option Base 0
Function BinaryFunction(Dlower, Dupper, Q, e)
Dim V, Re, tol, D1, D2, B1, B2, i, err
tol = 10 ^ -7: err = Abs(Dupper–Dlower)
i = 0
While err > tol And i < 50
D1 = (Dupper–Dlower) / 2–tol + Dlower: D2 = (Dupper–
Dlower) / 2 + tol + Dlower
B1 = Bisection2(0.0001, 1, e, D1, Q):
B2 = Bisection2(0.0001, 1, e, D2, Q)
i = i + 1
If B1 = B2 Then
Dlower = D1: Dupper = D2
Else
If B1 > B2 Then
Dlower = D1
Else
Dupper = D2
End If
End If
One-Dimensional Optimisation 51
err = Abs(Dupper–Dlower)
Wend
BinaryFunction = (D1 + D2) / 2
End Function
Using the previous code, D* = 0.207. To get the minimum of f, one can call the
function Bisection2 and get fmin = 0.007059. The code can run for a substantially
long time if the initial region is large. One of the disadvantages of the previous bisec
tion code is that two initial limits are fixed. These two limits are unnecessarily wide
apart to ensure a solution exists in all values of D. The large initial region will require
many iterations during the bisection method. Applying the scanning method with
double step size might significantly reduce the computing time in this case.
Answer
Insert the index into the code so the program gives the number of iterations.
For example, for Code 4.1, change the last line to
Dim output(1,2)
output(1,1) = Round((D1 + D2) / 2, 1)
output(1,2) = i
GoldenSection =output
Hints
First, the Fibonacci numbers are generated up to the required limit: ( b a ) / e, where
ε is the tolerance. In Example 4.1, the limit is 80. So the required Fibonacci numbers
are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89.
52 Calculations for Process Engineering Using Excel VBA
For each iteration, the selection of x1 and x2 is based on the two neighbouring Fib
onacci numbers: x1 = b Fi /Fi+1 ( b a ) and x2 = a + Fi /Fi+1 ( b a ) . For example,
the first iteration is based on F10 (55) and F11 (89).
Hints
Modify the last line of the code “BinaryFunction = ( B1 + B2 ) / 2 ”. Alternatively, the
code can give fmin and D * by employing an output matrix, as in Example 4.4.
Solution
Excel has a rounding function, MROUND, which allows rounding a number to a
specified multiple. For example, using the following code with tol = 0.25 will result
in D = 4.5 .
5.1 INTRODUCTION
While the previous methods in Chapter 4 deal with one-dimensional optimisation,
on the other hand, many practical problems require multiple-dimensional optimisa
tion. In general cases, these multiple-dimensional problems are challenging to solve.
However, there is a class of optimisation in which all equations are linear. This type
of optimisation can be solved by “linear programming” algorithms. The most popu
lar one is the simplex algorithm.
The simplex algorithm is widely used for solving linear programming problems
and is still considered one of the most efficient methods for solving linear program
ming problems. A linear programming problem is an optimisation problem where
we seek to maximise or minimise a linear objective function subject to a set of linear
constraints. The simplex algorithm works by iteratively moving from one basic fea
sible solution to another in a way that maximises or minimises the objective function.
One of the strengths of the simplex algorithm is its ability to handle large-scale linear
programming problems.
Subject to:
x1 < 4
2x1 + x2 + x3 < 10
2x1 + 2x2 + x3 < 16
All variables are non-negative.
54 DOI: 10.1201/9781003364511-5
Linear Programming 55
Solution
The first step is to convert the inequalities to equalities and then present the table
form. The inequality constraints are converted to equations by adding slack variables.
x1 + x4 = 4 Eq. 5.2
Consequently, the objective and equations can be presented in the matrix form.
The simplex algorithm can be applied by improving the feasible solution. The prob
lem is presented in the matrix form, Table 5.1, and entered into an Excel spreadsheet.
To simplify the explanation, the variables can be classified as either basic or
non-basic variables. In Table 5.1, the three variables without coefficients (x4, x5, x6) are
basic variables. The other variables (x1, x2, x3) are non-basic variables. The simplex
method employs pivoting steps in a repeating manner. The purpose of each pivoting
step is to exchange one basic variable and one non-basic variable (Nawrocki 2013).
The pivoting includes three elementary steps:
TABLE 5.1
The Input of the Simplex Problem
–z x1 x2 x3 x4 x5 x6 B
1 20 16 12 –10
1 0 0 1 0 0 4
2 1 1 1 10
2 2 1 1 16
56 Calculations for Process Engineering Using Excel VBA
The pivoting is repeated until all c are negative. It should be noted that cycling can
happen when steps 2 and 3 have several equal choices. To prevent cycling, one can
use Bland’s anticycling rule:
The procedure is implemented in the following code. The input is a table (contain
ing all elements in Table 5.1 except the headings), and the output is a table of the
same size. The code is divided into three parts for the readers to follow. The first one
is validating the dimension and properties of the inputs.
After checking the matrix, the code needs to check if there is a positive coefficient
in the first row (Code 5.2). If there is none, the current solution cannot be improved.
Linear Programming 57
In the next step, a basic and non-basic variable will be determined to be exchanged
with each other (Code 5.3).
After the first iteration, the output will become Table 5.2. After pivoting on A(1,2),
the basic variables are { x1 , x5 , x6 }.
TABLE 5.2
Table after First Iteration
–z x1 x2 x3 x4 x5 x6 B
1 0 16 12 –20 0 0 –90
0 1 0 0 1 0 0 4
0 0 1 1 –2 1 0 2
0 0 2 1 –2 0 1 8
The procedure is repeated until all coefficients in the first row are non-positive.
Linear Programming 59
TABLE 5.3
Table after the Fourth Iteration: The Procedure Stops since all c Values Are
Non-Positive
–z x1 x2 x3 x4 x5 x6 B
1 –4 0 0 0 –8 –4 –154
0 2 0 1 0 2 –1 4
0 0 1 0 0 –1 1 6
0 1 0 0 1 0 0 4
The final output is in Table 5.3. In this table, the three non-basic variables are x1,
x5 and x6. Next, the user can work out the optimised solution from the final form. In
Table 5.3, the three variables with zero coefficients (x2, x3, x4) are basic variables. The
solution corresponds to the combination in which the values of non-basic variables
are zero, and the values of basic values are determined by the other rows of the table.
The values of basic variables are equal to the corresponding values in column B
(since all coefficients of basic variables are 1). For Table 5.3, the B column results in
x2 = 6, x3 = 4, and x4 = 4. Since we only need the actual variables in the original prob
lem, the solution is x1 = 0, x2 = 6, x3 = 4. The optimised value of z equals –B(1) = 154.
TABLE 5.4
Heat Data for Heat Exchange Networks
Stream Type Ts Tt (°C) Flow Duty (kW)
H1 Hot 150 60 2.0 180
H2 Hot 90 60 8.0 240
C1 Cool 20 125 2.5 262.5
C2 Cool 20 100 3.0 225
UH1 Hot utility 200 — —
UC1 Cool utility 20 — —
The problem can be converted into a linear optimisation (Pillai and Bandyo
padhyay 2007) with eight flow variables, four equality constraints and two ine
quality constraints. The two utilities, UH and UC, are numbered at heating node 1
and cooling node 1. Other streams are numbered subsequently. Let aij be the flow
from hot stream i to cool stream j. Each non-zero aij represents a heat exchanger.
The required temperatures can be achieved by using the hot utility to heat the
two cool streams and the cold utility to cool the two heat streams. This scenario
is represented by Figure 5.1(a). In such a setup, the total energy requirement is
unnecessarily high. To save energy, the plant operator may want to cross some
hot and cool streams. The net energy saving can be achieved by minimising the
utility energy.
The objective is to minimise the duty of the cold utility:
FIGURE 5.1 Heat exchange network. (a) All heating/cooling is done by the two utility
streams. (b) Minimisation of heating duty.
Linear Programming 61
Furthermore, one needs to consider the physical constraints. For instance, the prob
lem can include new constraints for temperatures between hot and cool streams.
The hot steam H2 has a very high heat duty, but it cannot heat cool streams to above
90°C (whereas the required temperatures for C1 and C2 are above 90°C). Hence, the
heat duty of the exchanger for H2 and C1 is limited to (90 – 20) × 2.5. Similarly, the
heat duty between H2 and C2 is limited to (90 – 20) × 3. Hence we have two other
inequalities:
We have two slack variables, S22 and S23, for these equations.
The nice feature of Tables 5.5 is that all coefficients are 1. Yet this isn’t easy to
work out the basic variables. The problem starts with four basic variables, which will
be replaced. However, after the pivoting, only two non-zero (negative) coefficients
are in row 1. It is not apparent which variables are non-basic. Hence, the code can be
modified to include the entered basic variables, which is AcC. The code inserts three
additional rows in the output matrix (Table 5.6).
TABLE 5.5
Heat Data for Heat Exchange Network: Initial Table
Z a12 a13 a21 a22 a23 a31 a32 a33 S12 S22 B
1 1 1 1 1 420
1 1 1 262.5
1 1 1 225
1 1 1 180
1 1 1 240
1 1 175
1 1 210
62 Calculations for Process Engineering Using Excel VBA
TABLE 5.6
Heat Data for Heat Exchange Networks: Final Answer
Z a12 a13 a21 a22 a23 a31 a32 a33 S12 S22 B
1 0 0 –1 0 0 –1 0 0 0 0 0
0 1 1 –1 0 0 –1 0 –0 0 0 67.5
0 0 1 –1 –1 0 0 0 1 0 0 45
0 –0 –0 1 1 1 0 0 0 –0 –0 180
0 –0 –1 1 1 0 1 1 0 –0 –0 195
0 –0 –0 0 1 0 0 0 0 1 –0 175
0 0 0 –1 –1 0 0 0 0 0 1 30
Function LinearP2(A)
Dim checkV(), sols()
ReDim M(1 To nRow + 3, 1 To nCol)
‘-----same as function LinearP
‘-----
M(nRow + 1, 1) = “No. of iter:”: M(nRow + 1, 2) = k
ReDim checkV(2 To nCol–1): ReDim sols(2 To nCol–1)
M(nRow + 2, 1) = “Variable”: M(nRow + 3, 1) = “Value “
For i = 2 To nCol–1
If M(1, i) = 0 Then
For j = 2 To nRow
If M(j, i) = 1 Then
checkV(i) = checkV(i) + 1
sols(i) = M(j, nCol) ‘if
more than 1 positive coef, sols(i) is the last one
End If
Next j
End If
If checkV(i) = 1 Then
M(nRow + 2, i) = “BV”: M(nRow +
3, i) = sols(i)
Else
M(nRow + 2, i) = “NBV”: M(nRow +
3, i) = ““
End If
Next i
LinearP2 = M
Else
LinearP2 = “No improvement”
End If
End Function
Linear Programming 63
TABLE 5.7
Pinch Analysis of Heat Exchange Networks, with Answers
Z a12 a13 a21 a22 a23 a31 a32 a33 S12 S22 B
1 0 0 –1 0 0 –1 0 0 0 0 0
0 1 1 –1 0 0 –1 0 –0 0 0 67.5
0 0 1 –1 –1 0 0 0 1 0 0 45
0 –0 –0 1 1 1 0 0 0 –0 –0 180
0 –0 –1 1 1 0 1 1 0 –0 –0 195
0 –0 –0 0 1 0 0 0 0 1 –0 175
0 0 0 –1 –1 0 0 0 0 0 1 30
No. of iter: 3 0 0 0 0 0 0 0 0 0 0
Variable BV NBV NBV NBV BV NBV BV BV BV BV 0
Value 67.5 180 195 45 175 30 0
The answers, including the values for basic variables, are given in Table 5.7.
This answer corresponds to the diagram in Figure 5.1(b). From these data, one can
calculate other properties of the proposed heat exchange network.
Subject to:
x1 < 4
2x1 + 2x3 < 10
2x1 + 4x2 + x3 < 16
x3 > 5
Solution
Since x3 can be both positive and negative, it can be replaced by x7 x8 (which are
both positive). Thus, a new slack variable is introduced:
x7 + x8 + x 9 = 5
The previous equation is combined with other equations to form the table.
z x1 x2 x7 x8 x4 x5 x6 x9 B
1 20 16 12 –12 –10
1 0 0 1 0 0 4
2 2 –2 1 10
2 4 1 –1 1 16
–1 1 1 5
Applying the code will get x1 = 4, x2 = 1.75 and x3 = 1 (from the values of x7
and x8 ).
As the truck has limitations on both weight and volume, determine how
much of each product to load to maximise the profit.
Solution
Introducing two slack variables, one can generate the following table.
–z A B x1 x2 B
1 5 7 0
Volume 50 80 1 10000
Weight 200 100 0 1 20000
Applying the previous code, the answers are B = 90.91 and A = 54.55. Since the
numbers of the transported products have to be integers, there will be four combina
tions around this combination. The best combination is (90, 55).
6 Roots of Systems of Linear
Equations
6.1 INTRODUCTION
Systems of linear equations are very common in engineering. For example, one can
find them with a series of reactors. However, the most common problems are related
to process heat transfer. A system of linear algebraic equations can be solved simul
taneously using a direct method such as Gaussian elimination. The Gaussian method
consists of two steps: forward elimination and back substitution. Forward elimination
reduces all elements in the bottom half to zero (such as in Eq. 6.1). Subsequently, the
solution is found from the last variable (xn to x1).
Eq. 6.1
Another direct method is the Gauss–Jordan method. In this method, the final
matrix contains nonzero values on the diagonal rather than a triangular matrix. The
rows are also normalised by dividing each one by its pivot element. The result is that
the identity matrix is formed, where all diagonal coefficients are the value 1. The
Gauss–Jordan method requires more work and more operations than Gauss elimi
nation. Gaussian elimination requires order n3/3 multiplications followed by back
substitution requiring order n2 multiplications. Gauss–Jordan elimination requires
order n3/2 multiplications (Lindfield and Penny 2019).
The methods can be problematic due to round-off errors and zero on the diagonal. For
many problems in process engineering, a successive substitution is more advantageous.
In these methods, the initial guesses (a combination of n values of unknowns) are gener
ated and then improved iteratively. These iterative substitutions require an initial guess of
the solution. Subsequently, this set of solutions is improved until the errors in all variables
are acceptable. The number of iterations of these methods depends on the initial guess
and the required error. An “educated” guess can significantly reduce the iterations and
multiplications. In addition, the number of iterations can be further reduced by employ
ing a relaxation factor. The VBA codes in this book will only cover the iterative methods.
DOI: 10.1201/9781003364511-6 65
66 Calculations for Process Engineering Using Excel VBA
all variables in the jth iteration are updated from the values of the ( j – 1)th iteration.
In the Gauss–Seidel, each variable is updated using the latest available values of the
other variables. In general, the Gauss–Seidel method provides faster convergence
than the Jacobi method.
The substitution formulas for a 4 × 4 system are presented by four separate
equations:
b1 a11 x1j 1 a11 x1j 1 + a12 x2j 1 + a13 x3j 1 + a14 x4j 11
x1j = + Eq. 6.3
a11 a11 a11
where k is the rate constant (1/hr), which depends on the operating condition
of the reactor.
The volumes and rate constants of the four reactors are tabulated in
Table 6.1. The feed conditions are C0 = 1 M, U0 = 1000 L/hr.
Part A� Prepare the system in a matrix form in an Excel spreadsheet.
Part B� Develop code to solve the system using the Gauss–Seidel method.
Part C� Repeat part B using the Jacobi method.
TABLE 6.1
Reactor Size and Conversion Constants
Reactor 1 2 3 4
Vol (L) 1000 1500 200 1000
k (h−1) 0.1 0.2 0.4 0.3
Solution
Part A. The problem requires a system of linear equations. At steady state, the mass
balances for each reactor are:
TABLE 6.2
Inputs for a System of Linear Equations
A B C D E F
1 Matrix a Cguess B
2 1100 1 1000
3 1000 –1450 150 1 0
4 1150 –1305.6 75.59866 1 0
5 1075.599 –1375.6 1 0
Using the VBA function in Code 6.1, a solution is found after 13 iterations
(tol = 10–10).
Part C� For the Jacobi method, the updating loop “Cin(row) = cnew(row)” is sep
arated from the calculating loop. Mathematically, the two methods require the same
number of calculations. In this instance, the numbers of iterations are also the same.
The function for the Jacobi method is presented in Code 6.2.
Wend
Cin(n + 1) = k: Cin(n + 2) = MaxErr
Jacobi = Cin
End Function
Using a tol of 10–10 and input in Table 6.2, the function in Code 6.1 gives the
answers after 25 iterations.
Solution
The VBA function in Code 6.1 is modified to include a relaxation factor. Using the
function in Code 6.3, one can vary λ to see the impact on the number of iterations.
Roots of Systems of Linear Equations 71
The number of iterations can be changed significantly using the VBA function in
Code 6.3 with different values of λ. For this particular system, an over-relaxation
with λ = 1.1 can reduce the number of iterations to 11.
of the mathematical equations from the physical system. The initial guess can also be
optimised from the physical characteristics. In some processes, the initial guess for the
new operating conditions can be used from previous conditions. These examples will
be demonstrated in the next chapter.
Hints
Re-arrange the function in Code 3.3 so that the output is only the number of iter
ation Cn(n + 1). Consequently, combine the code with an optimisation method in
Chapter 4. The smallest number of iterations should be 8, with λ between 1.0381 and
1.0389. The relations between λ and k can also be plotted in Figure 6.2.
FIGURE 6.2 Relationship between relaxation factor and the number of iterations.
Roots of Systems of Linear Equations 73
Hints
An obvious solution is Cg(i) = B(i)/A(i,i). If A is a diagonally dominant matrix, these
guesses are closer to the final answer than random guesses. The code will need A and
B matrices only. Hence, the initial values for the first iteration can be replaced.
For row = 1 To n
Cin(row) = b(row)/a(row, row)
Next row
7 Applications of Systems
of Linear Equations
7.1 INTRODUCTION
The solution of linear equations can be combined with other methods to solve com
plex problems. Furthermore, the system of linear equations can be used to impose
relations between the various partial derivatives of a multivariable function. Such
problems are often found in the process of heat transfer. This chapter will present
these problems and solutions.
74 DOI: 10.1201/9781003364511-7
Applications of Systems of Linear Equations 75
pivoting is used to swap two rows of coefficients when necessary (to place the max
imum coefficient of a given column in the proper row). However, as seen in the fol
lowing examples, some systems already meet the requirement during the formulation
process from the physical equations.
Solution
In this case, a bisection code can be used. All elements of matrices A and B in the previ
ous example have to be calculated within the VBA code. Please note that only two ele
ments in matrix A depend on U4R. Subsequently, the bisection method can be applied.
First, the data are entered into the specified cells of an Excel spreadsheet (Table 7.1)
The first section of the VBA code is used to generate the matrices A, B and Cguess
before running the Gauss–Seidel or Jacobi method. The elements of A and B are cal
culated according to the mass balances of the reactors. The output of the VBA code
TABLE 7.1
Reactor Sizes, Constants, and Flow Conditions
A B C
1 Reactor volume and kinetic constant
2 Reactor Vol (L) k (h−1)
3 1 1000 0.1
4 2 1500 0.2
5 3 200 0.4
6 4 1000 0.3
7 Flow conditions
8 CA0 (mol/L) 1
9 U0 (L/hr) 1000
10 U3R (L/hr) 150
76 Calculations for Process Engineering Using Excel VBA
Ca0 = Range(“B8”).Value
U0 = Range(“B9”).Value
U3r = Range(“B10”).Value
Lo = Mi: c1 = c3
End If
Next i
‘*****************************************
BisectionX = Mi
End Function
Using the previous code with a tolerance of 10–4, the required U4R is determined
at 75.2794 L/hr and C4 = 0.50000 M. With a tolerance of 10–6, the optimised U4R is
determined at 75.5018 L/hr and C4 = 0.50000 M. The sensitivity of the correlation
between C4 and U4R is a key advantage of employing recycle streams in reaction
engineering.
Ñ 2T = Q / k Eq. 7.1
where T is the temperature at a point in the body, Q is the heat transfer rate per unit
volume and k is the material’s thermal conductivity.
In Eq. 7.1, Ñ 2T = Q / k represents the Laplacian of T, which is the sum of the
second partial derivatives of T with respect to the x and y coordinates. The equation
can be solved using numerical methods, such as finite difference, finite element or
boundary element methods. These methods discretise the object or fluid into a grid of
points, and the temperature at each point is calculated based on the temperature and
heat flux at neighbouring points. Since the temperatures of all points are interlinked,
a system of equations must be solved simultaneously.
Solution
For 2-dimensional steady-state heat problems, there is no heat accumulation at any
point. The temperature of the boundary nodes is the same as the surrounding envi
ronment. Therefore, the values of temperature at the four corners are ignored. For any
interior nodes, the temperature is given the balance of the four surrounding nodes.
For instance, the temperature of node (1,1) is given by:
One can use the previous VBA functions, such as Code 6.1 (Gauss–Seidel method),
to solve the previous system. A small modification can be done, as shown in Code
Applications of Systems of Linear Equations 79
7.3, to have the number of outputs exactly the same as the number of equations and
displaced in the vertical direction.
Using the VBA function in Code 7.3, the answer will be given in Table 7.2. The
results are also presented graphically in Figure 7.2.
TABLE 7.2
The Temperature of Internal Nodes
T11 42.76562
T21 33.16739
T31 33.8828
T12 63.07809
T22 56.15845
T32 52.40958
T13 78.52565
T23 76.07029
T33 69.61997
Part A� Calculate the temperature profile in the vertical direction, from the oil
surface to 1.2 cm depth, after 1, 2, 5 and 10 mins.
Part B� Calculate the temperature at the points of 1.2 mm from the surface and
compare it with experimental data (Shibata et al. 2018).
Solution
The heat diffusion equation is given by:
¶T ¶2 T
=k 2 Eq. 7.3
¶t ¶x
where k is the thermal diffusivity of water, which varies with temperature.
The vertical domain of the water body is divided into n nodes. Node 1 is at the
1.2 cm depth, and node n is the water surface. At t = 0, all temperatures, except node
n, equal 80°C.
The dimensionless parameter, λ, is given:
Dt
l=k Eq. 7.4
Dx 2
Applications of Systems of Linear Equations 81
For internal nodes (from 2 to n – 1), the heat diffusion is discretised as:
lTi l1+1 + 2 (1+ l ) Ti l +1 lTi l+1+1 = lTi l1 + 2 (1+ l ) Ti l + lTi l+1 Eq. 7.5
The previous system is arranged into a system of n equations. The n × n matrix has
non-zero values in the next diagonal and is often known as the tridiagonal matrix.
The procedure is repeated m times to get the answers in m seconds (Code 7.2). This
code consists of a separate function, SS(T, delx, delt), to calculate the value of λ at
each node temperature.
For i = 2 To m
MaxErr = 1: k = 1
‘-----------
While MaxErr > tol And k < 1000
k = k + 1: MaxErr = 0
‘--------------
a(1, 1) = 2 + 2 * SS(Tin(1), delx, delt): a(1, 2) = -2
* SS(Tin(1), delx, delt)
82 Calculations for Process Engineering Using Excel VBA
FIGURE 7.4 The temperature at 12 mm from the surface; experimental data were obtained
from Shibata and coauthors (2018).
8 Solving Systems of
Non-Linear Equations
8.1 INTRODUCTION
A system of non-linear equations is a set of equations where at least one is non-
linear, that is, contains a non-linear function such as a polynomial, trigonometric or
exponential function. Unlike linear equations, these equations cannot be solved using
simple algebraic techniques, and numerical methods must be used to obtain solu-
tions. The chapter presents several methods to solve systems of non-linear equations.
While some of the methods can be generalised, the success of a particular method
will depend on the nature of the equations and initial guesses. Furthermore, it should
be noted that many systems cannot be solved. Applying a numerical code to a general
system could lead to unfruitful outcomes.
u ( x, y ) = 0 Eq. 8.1a
v ( x, y ) = 0 Eq. 8.1b
¶vi ¶u
ui vi i
¶y ¶y
xi+1 = xi Eq. 8.2a
¶ui ¶vi ¶ui ¶vi
¶x ¶y ¶y ¶x
DOI: 10.1201/9781003364511-8 85
86 Calculations for Process Engineering Using Excel VBA
¶u i ¶v i
vi ui
y i +1 = y i ¶x ¶x
Eq. 8.2b
¶u i ¶v i ¶u i ¶v i
¶x ¶y ¶y ¶x
where the partial derivatives are evaluated at the values of xi and yi.
An analog to the secant method in Chapter 2 can be used to avoid differential
equations. In this case, two different step sizes, delx and dely, can be applied. VBA
code was developed in the following example to calculate the binary adsorption at
the air/water surface (Le et al. 2012). It should be noted that the step sizes (del1 and
del2) and initial values need to be selected appropriately. If these steps are too large,
the solution can be unstable.
q1
K1C1 =
(1 q1 q2 ) 1
r { (
exp 2A1q1 2A12q 2 + (1 r1 ) A1q12 + A2q 22 + 2A12q1q 2 )} Eq. 8.3
q2
K 2 C2 =
(1 q1 q2 )
r2 { (
exp 2A2q 2 2A12q1 + (1 r2 ) A1q12 + A2q 22 + 2A12q1q 2 )} Eq. 8.4
RT
g = 72 ln (1 q1 q 2 ) A1q12 + A2q 22 + 2A12q1q 2 Eq. 8.5
w
where R and T are the gas constant and temperature, respectively.
For a particular system of surfactant mixture, the parameters are given
in Table 8.1. Calculate the surface tension of this mixture at 25°C when
c1 = 9.6´10 –3 M and c1 =1.7 ´10 – 4 M .
Solving Systems of Non-Linear Equations 87
TABLE 8.1
Parameters for Binary Adsorption of Two Surfactants
A B C D E F G
1 Γm,1 (mol/m2) Γm,2 (mol/m2) K1 (M−1) K1 (M−1) A1 A2 A12
2 1.5 × 10–5 1.1 × 10–5 40.1 2596 0 0.2 –0.963
Solution
The problem requires solving two equations simultaneously. These two equations are
not in an explicit form. However, the two functions are the same, with interchanging
roles between c1 and c2. Hence, a common VBA function, f457, can be used.
Err = u ^ 2 + v ^ 2: i = i + 1
Wend
a(0, 0) = theta1: a(0, 1) = theta2: a(0, 2) = i:
a(0, 3) = (theta1 + theta2)/(theta1 / w1 + theta2 / w2)
jacobian457 = a
End Function
88 Calculations for Process Engineering Using Excel VBA
Using theta1 = 0.282 and theta2 = 0.321, the solution is obtained after six iter
ations: theta1 = 0.183, theta2 = 0.192 and ω = 77271 (m2/mol). From Eq. 8.5, the
surface tension is calculated as 55.0 mN/m.
C2 H 4 + HCl ® C2 H 5 Cl
The process can be simplified in the following diagram, adapted from example
10.2–3 (Felder and Rousseau 2005). The fresh feed contains 100 kgmol/h of
HCl and C2H4 mixture. The fresh feed is mixed with the recycle stream before
entering the reactor. The single-pass ethylene conversion is 90%. After the
reactor, the stream is separated into Product (containing C2H5Cl only) and
Stream S-4 (containing C2H4 and HCl). Stream S4 is split into Waste and
Recycle streams. Streams S4, Waste and Recycle have the same composition.
The ethylene molar fraction in the feed is 52%, and the waste stream has a flow
rate of 8 kgmol/h.
Find the molar flows for two species in the recycle stream.
Solving Systems of Non-Linear Equations 89
FIGURE 8.1 Acetylene production with a Recycle stream and two unknowns.
Solution
The flowsheet is the same as in Example 3.2. For example, if the molar fraction is
50%, the solution is the same as in Example 3.2 and can be solved by a bisection
code. In this case, however, since the molar fractions of the feed are not equal, the
solution will have unequal flows in the Recycle stream (Figure 8.1).
For any combination of the R1 and R2, the material balances allow the calculation
of the tear stream (R1cal and R2cal). Consequently, the program needs to solve the
following equations simultaneously:
difR1 = Rt(1)–R(1)
End Function
Dim ratio
R(1) = Rg1: R(2) = Rg2 ‘tear stream
S1(1) = feed * fraction + R(1): S1(2) = feed * (1–frac
tion) + R(2)
S2(1) = S1(1)–S1(1) * Conv: S2(2) = S1(2)–S1(1) * Conv:
S2(3) = S1(2) * Conv
S4(1) = S2(1): S4(2) = S2(2)
ratio = S4(1)/(S4(1) + S4(2))
Rt(1) = S4(1)–W * ratio: Rt(2) = S4(2)–W * (1–ratio):
difR2 = Rt(2)–R(2)
End Function
It should be noted that these functions include the same calculation until the last
line. With these two functions, the four elements of a Jacobian matrix can be obtained
and used to calculate the next set of R1 and R2. The iteration is repeated until the
total error is sufficiently small.
Code 8�3� System of two non-linear equations (in combination with tear
analysis)�
Function jacobian(R1i, R2i, feed, fraction, Conv, W)
Dim i, Err, del1, del2, u, v, dudx, dudy, dvdx, dvdy, a(0, 2)
With initial guesses of (5,5), the code gives R1 = 3.111 kgmol/h and R2 = 9.333
kgmol/hr after five iterations. If the fraction is changed to 0.5, the code should give the
same answer as in Example 3.2. While the method gives a quick solution for this case,
extending it to more variables (for example, three or four species in the tear stream) will
be difficult. Therefore, in the next section, an empirical search method is introduced.
Solution
In this case, the previous example is used to demonstrate the method. Instead of
solving two equations simultaneously, the harmony search aims to minimise the sum
of squares of difference:
The function in the previous equation is a total difference between guessed and cal
culated values of all unknowns in the tear stream. The function is evaluated in Code
8.4, using the same calculation steps in Code 8.2.
Consequently, the harmony search can be applied (Codes 8.5 to 8.6). The step
by-step is explained in the following. First, a set of 100 (HMS) combinations of x1
and x2 are generated randomly. It should be noted that the VBA function RND has
a small range of randomness. Therefore, one can improve the process by adding the
function RANDOMIZE before using RND. Furthermore, the code can indirectly use
the Excel spreadsheet function by typing RAND() into a cell and then EVALUATE
that cell. Next, the objective functions of these combinations are evaluated and stored
in the HM array (Code 8.4). The code has three key parameters: HMS (Harmony
Memory Size), HMS ≥ 1; HMCR (Harmony Memory Considering Rate), 0 ≤ HMCR
≤ 1; and PAR (Pitch Adjusting Rate), 0 ≤ PAR ≤ 1 (Ingram and Zhang 2010).
Code 8�5� Harmony search with two variables (the function diffR2 is
defined in Code 8�4)� Section 1: generate the initial sets of solutions�
Function harmony2(LowerR, UpperR, feed, fraction,
Conv, W)
Dim limit(5, 3), x(5), ND
Dim HM(500, 3), HMS, HMCR, PAR, MaxIte
Dim d1, sol, i, j, iter, rand
Dim hmax, hmax _ n, hmin, hmin _ n, out(4, 4)
Code 8�6� Harmony search with two variables� Section 2: find the maxi
mum and minimum values from the initial sets�
hmax _ n = 1: hmax = HM(1, 3)
For i = 2 To HMS
If HM(i, 3) > hmax Then
hmax _ n = i
hmax = HM(i, 3)
End If
Next i
In the next step, a new combination is obtained randomly. A random value is gen
erated and compared with the two limits, HMCR and PAR. Depending on the value
of RND, either one of three operations will be carried out:
At the end of the selection, the objective function of the new combination is evalu
ated and compared against the worst combination in the existing sets. Once the re
quired number of iterations is reached, the improvement process stops. Finally, the
best combination with sets is identified and exported.
Code 8�7� Harmony search with two variables� Section 3: generating and
comparing the new combination�
---------------
For iter = 1 To MaxIte-1
Randomize: rand = Rnd
For j = 1 To ND
If rand >= HMCR Then ‘Random Searching
x(j) = limit(j, 1) + (limit(j, 2)–
limit(j, 1)) * rand
Else
d1 = Int(HMS * rand) + 1
x(j) = HM(d1, j)
If rand < PAR Then ‘Pitch Adjusting
d1 = (limit(j, 2)–limit(j, 1))/
limit(j, 3)
x(j) = x(j) + d1 * (rand–PAR /
2)
End If
End If
Next j
sol = diffR2(x(1), x(2), feed, fraction, Conv, W)
If sol < hmax Then ‘if new Sol is smaller than hmax,
replace hmax
For j = 1 To ND
HM(hmax _ n, j) = x(j)
Next j
HM(hmax _ n, 3) = sol
End If
Next iter
In this code section, RANDOMIZE is used before calling the RND again. The
value (“rand”) is used for the three calculations in the three improving options. Tech
nically, different random numbers can be generated and used for these calculations,
which might improve the solution.
With limits at 3 and 10, the code can generate the answers as in Table 8.2. It
should be noted that the answers will be different when the code is repeated.
The two flow rates are close to the answer from the secant method and can be
improved by increasing the number of iterations and other parameters (HMS,
HMCR and PAR).
TABLE 8.2
Harmony Search Output
Min from the Initial Sets Max from the Initial Sets 0 0
0.099774994 113.9915897 0 0
Number of iter x1 x2 Error
10000 3.105824475 7.288284783 0.098218223
96 Calculations for Process Engineering Using Excel VBA
Answer
First, a new function is needed to replace both difR1 and defR2. The func
tion will return two values simultaneously as two elements of an output array
(2-dimensional). Consequently, the main function will call the corresponding
elements in a Jacobian procedure. Therefore, the output array, even with only
two elements, needs to be in a 2-dimensional form.
Answer
By increasing the number of sets, the best solution is improved significantly.
For instance, Table 8.3 shows that HMS = 500 and MaxIte = 100 can provide
a better solution. However, in this case, the harmony search does not improve
the best solution from the random set. Perhaps some of these problems can be
solved by many random trials of guesses, similar to the search algorithm in
Example 12.3.
TABLE 8.3
Harmony Search Output
Min from the Initial Sets Max from the Initial Sets 0 0
0.006903335 126.048336 0 0
Number of iter x1 x2 Error
100 3.161868572 9.779379845 0.006903335
9 Solving Ordinary Differential
Equations
9.1 INTRODUCTION
An ordinary differential equation (ODE) is a differential equation containing one
or more functions of one independent variable and the derivatives of those func
tions. The equations are used to describe many physical processes. For example,
the equations play a central role in predicting the specie balances for chemical reac
tions. Consequently, solving ODEs is fundamental to reactor design and process flow
sheeting. The order of the ODEs is defined as the highest order of any differential
term. Any nth-order ODE can be expressed in the system of n first-order ODEs.
Numerical methods for solving ordinary differential equations are techniques used
to approximate the solution of an ODE. These methods involve approximating the
derivative or differential equation with a mathematical expression that can be solved
numerically. Many numerical schemes are available for solving ODEs, each with
advantages and disadvantages.
dy
= f ( x, y ) Eq. 9.1
dx
where y = y0 at x = x0 .
The one-step method will divide the domain, from x = x0 to x f , into m steps with
a constant step size of h. The relationship between h and m is defined as:
h= ( xf x0 ) / m Eq. 9.2
The method will then approximate the values of y at those steps sequentially. These
one-step approximation methods are named the Runge–Kutta (RK) methods for dif
ferential equations. There are many variations, which are sub-classified according
to the order of the scheme. For example, an nth-order RK method will require n
evaluations within each step and has local and global errors on the order of hn+1 and
hn, respectively. There is only one first-order RK method, Euler’s, which is the most
straightforward numerical method for solving ODEs.
Mathematically, Euler’s prediction is:
y ( x + h ) = y ( x ) + f ( x, y ) h Eq. 9.3
DOI: 10.1201/9781003364511-9 97
98 Calculations for Process Engineering Using Excel VBA
Solution
Using Euler’s method, the solution can be found with simple VBA code (Code 9.1).
For i = 1 To n
matrix(i, 0) = matrix(i–1, 0) + dx
matrix(i, 1) = matrix(i–1, 1) + ff(matrix(i–1, 0),
matrix(i–1, 1)) * dx
Next i
RK _ 1 = matrix
End Function
Function ff(x, y)
ff = Cos(x)
End Function
Figure 9.1 shows that solution accuracy increases with the reduced step size, h.
However, smaller step sizes will increase the number of iterations and, thus, com
putational time. The curves also demonstrate two types of errors in the method: the
local truncation error and the accumulative truncation error. For Euler’s method, the
local error is on the order of h2, and the global error is on the order of h (Chapra
and Canale 2010). For many problems, the required step size might be too small
and result in numerous iterations. Consequently, there are other RK methods in the
literature.
where yi+0.5 is the slope of the midpoint between xi and xi+1 and is given by:
VBA code for the improved polygon method is given in Code 9.2.
100 Calculations for Process Engineering Using Excel VBA
For i = 1 To n
matrix(i, 0) = matrix(i–1, 0) + dx
x _ m = matrix(i–1, 0) + dx / 2
y_m = matrix(i–1, 1) + ff(matrix(i–1, 0),
matrix(i–1, 1)) * dx / 2
matrix(i, 1) = matrix(i–1, 1) + ff(x _ m, y _ m) * dx
Next i
RK _ 2 = matrix
End Function
é1 ù
yi +1 = yi + ê ( k1 + 2k2 + 2k3 + k4 ) ú h Eq. 9.6
ë6 û
where
k1 = f ( xi , yi ) Eq. 9.7a
æ 1 1 ö
k2 = f ç xi + h, yi + k1h ÷ Eq. 9.7b
è 2 2 ø
æ 1 1 ö
k3 = f ç xi + h, yi + k2 h ÷ Eq. 9.7c
è 2 2 ø
k4 = f ( xi + h, yi + k3 h ) Eq. 9.7d
VBA code for the method is given in Code 9.3. The code and VBA functions in
Codes 9.1 and 9.2 compare the three methods, as demonstrated in Figure 9.2.
Solving Ordinary Differential Equations 101
FIGURE 9.2 Comparison between Euler’s, improved polygon and fourth-order Runge–
Kutta methods.
For i = 1 To n
m(i, 0) = m(i–1, 0) + h
k1 = ff(m(i–1, 0), m(i–1, 1))
k2 = ff(m(i–1, 0) + h / 2, m(i–1, 1) + k1 * h / 2)
k3 = ff(m(i–1, 0) + h / 2, m(i–1, 1) + k2 * h / 2)
k4 = ff(m(i–1, 0) + h, m(i–1, 1) + k3 * h)
m(i, 1) = m(i–1, 1) + (k1 + 2 * k2 + 2 * k3 + k4) * h / 6
Next i
RK _ 4 = m
End Function
A general equation might have sections with dramatic and gradual changes.
Consequently, the coder must balance step size (and the number of steps) and accu
racy. One way to achieve this is by using an adaptive step size. In this approach,
the step size of each increment is determined by estimating the local absolute error.
If only one RK method is used, the absolute error is unknown. However, com
bining two RK methods with different orders can control the error. In theory, any
two RK methods can be selected. However, there are certain combinations in which
the evaluations are nested to reduce the number of function evaluations. One of the
well-known combinations is the Runge–Kutta Fehlberg method, which combines a
fourth- and fifth-order Runge–Kutta method.
On the other hand, the easiest way is combining a first-order and second-order
method. This section uses the combination to demonstrate the adaptive step size.
Within each iteration, the method starts with a guessed step size, hpresent. Conse
quently, the absolute difference between the full-step and the two half-step values is
the error estimate, errc. By comparing with the user-specified tolerance, errd, the step
size is adjusted (Press and Teukolsky 1992):
a
é errd ù
hnew = 0.95 hpresent ê ú Eq. 9.8
ë errc û
In Eq. 9.8, α is the adjustment factor, which equals 0.2 when errc > errd, and 0.25
when errc < errd. Using the formula, the step size is adjusted until the desired ac
curacy is given by
10 ( x 2 )
2
y¢ = 15e – 0.8y
Solution
The Euler method in Code 9.1 can be modified to combine with function fff in Code
9.4. The fourth-order Runge–Kutta and adaptive methods are presented in Code 9.4.
Solving Ordinary Differential Equations 103
Code 9�4� Adaptive step size with Euler and second-order method�
Option Base 0
Function fff(x, y)
fff = 15 * Exp(-(x–2) ^ 2 / 0.1)–0.75 * y
End Function
Function RK _ 42(x0, y0, h, Xmax)
Dim m(), i, n, k1, k2, k3, k4
For i = 1 To n
m(i, 0) = m(i–1, 0) + h
k1 = fff(m(i–1, 0), m(i–1, 1))
k2 = fff(m(i–1, 0) + h / 2, m(i–1, 1) + k1 * h / 2)
k3 = fff(m(i–1, 0) + h / 2, m(i–1, 1) + k2 * h / 2)
k4 = fff(m(i–1, 0) + h, m(i–1, 1) + k3 * h)
m(i, 1) = m(i–1, 1) + (k1 + 2 * k2 + 2 * k3 + k4) * h / 6
Next i
RK _ 42 = m
End Function
TABLE 9.1
Adaptive Step Size
A B C D
h x y k
0.5 0 0.5
0.23497 0.23497 0.411886106 4
0.23497 0.469941 0.339300329 4
0.23497 0.704911 0.279506296 4
0.234811 0.939721 0.230283213 4
0.219514 1.159236 0.192413513 4
0.119156 1.278392 0.176739477 4
0.064968 1.34336 0.173465187 5
0.048407 1.391767 0.17690453 5
0.03784 1.429607 0.185924458 6
0.033484 1.463091 0.200662556 6
0.030896 1.493988 0.221957736 6
0.027883 1.521871 0.249633028 7
0.027085 1.548956 0.285865638 7
0.026812 1.575768 0.33270589 7
0.02698 1.602748 0.392888656 7
0.027554 1.630302 0.470063829 7
0.028543 1.658845 0.569148304 7
0.030004 1.68885 0.696886125 7
Please note that the adaptive_E function in Code 9.4 only does one step. To get
the whole function from 0 to 4, the function in Code 9.4 is called continuously in a
table form. A section of the table is shown in Table 9.1. The VBA function also gives
the number of adjustments, k, at each step. The predetermined error plays a clear role
in this value. In Table 9.1, the starting step, h, is fixed at 0.5, and the required relative
error, ErrA, is 1%. The code is designed so that this input can be changed easily.
The adaptive method is plotted against Euler’s, fourth-order RK and analytical
solutions in Figure 9.3.
At first glance, the adaptive step method requires many iterations, with some
improved accuracy over Euler’s method. However, the combined first- and second-
order methods have errors on the order of h3, which is still larger than a fourth-order
Runge–Kutta method. Hence, the adaptive method is less accurate than the fourth-
order RK, as shown in Figure 9.3.
On the other hand, the adaptive method has an advantage when the whole function
is needed. For instance, when function behaviour is used to integrate a curve under
the function, the accuracy along the function is more important than the final value at
the upper limit. This is demonstrated in the plug-flow reactor design in Chapter 10.
Solving Ordinary Differential Equations 105
Finally, the calculation can be optimised by manually selecting the step size.
For example, after applying Euler’s method with a constant step size of 0.4, dra
matic changes are observed in the region between 1 and 3. Consequently, the whole
region between 0 and 4 can be divided into three sections: (0,1), (1,3) and (3,4). The
step sizes in these three regions are selected at 0.2, 0.05 and 0.2, respectively. The
resulting prediction with Euler’s method is demonstrated in Figure 9.4. The method
106 Calculations for Process Engineering Using Excel VBA
has a better prediction than the adaptive method while having a very simple calcu
lation. The approach requires a visual justification of the important regions. Such
an approach is very helpful for a system of ODEs, such as reactor modelling in
Chapter 10.
The feed is added continuously at a volumetric flow rate of 240 L/h and tem
perature of 305 K. The feed contains A at a concentration of 4 mol/L. The
reactor has a heat exchanger with UA = 35000 cal/h K and an exchange (air)
temperature of 298 K. Initially, there is 100 dm3 solution in the reactor, with 1
mol/dm3 of A and 1 mol/L of the catalyst.
Part A� Calculate and plot the chemical concentrations and temperature as a
function of time from zero to 1.5 hours.
Part B� Calculate the maximum concentration of B and the corresponding
reaction time.
Solution
Part A� The problem can be solved using a system of four ODEs and several equa
tions. The four ODEs account for the changes of three chemicals and temperature.
Heat balance equations describe the transient heat of the two reactions and the heat
input. First, the values of parameters are input into an Excel spreadsheet (Table 10.1).
TABLE 10.1
Parameters of Reactions, Flow Rate, Temperature and Initial Conditions
A B C
1 Reactor Variables Unit
2 Cao 4 mol/dm3
3 To 305 K
4 vo—flowrate 240 dm3/h
4 Ta—temp of air 298 K
5 V_in 100 dm3
6 R 1.987 cal·K−1·mol−1
7 E1 9500 cal/mol
8 E2 7000 cal/mol
9 Tref1 320 K
10 Tref2 300 K
11 k1a 1.25 h−1
12 k2b 0.08 h−1
13 Energy variables
14 delHra −6500 cal/mol A
15 delHrb 8000 cal/mol B
16 UA 35000 cal/hK
17 Cpa 30 cal/molK
18 Cpb 60 cal/molK
19 Cpc 20 cal/molK
20 Cpcatalyst 35 cal/molK
21 N_cat 100 mol
110 Calculations for Process Engineering Using Excel VBA
While these parameters can be included in the VBA function as arguments, such
an arrangement will make the function more complicated and prone to error when
calling the macro. In this instance, the values of parameters are assigned to the VBA
variable using the Range object. The positions of the cells need to be fixed.
For i = 1 To n
M(i, 0) = M(i–1, 0) + dt: M(i, 1) = M(i–1, 1) + dt * v0
r1 = -k1a * Exp(E1A/R * (1 / T1–1 / M(i–1, 5))) *
M(i–1, 2)
r2 = -k2b * Exp(E2B/R * (1 / T2–1 / M(i–1, 5))) * M(i–1, 3)
Part B� From the graph in Figure 10.1, the concentration of B has a maximum of
around 0.6 h. To determine this point precisely, we can combine the ODE code with
region elimination code.
First, the function in Code 10.1 is revised so that the output only contains con
centration B at time tmax. The new function can be named dablTdt_2 (Code 10.2).
The function dabcTdt_2 is essentially the same as in Code 10.1, except for output
(M(n,3) instead of M). Consequently, the function is a subfunction within a golden
section search. The final answers are CB_max = 1.191 and tm = 0.6438 h.
output(0) = (t _ l + t _ h) / 2: output(1) =
dabcTdt _ 2(delt, output(0))
It should be noted that the “For Next” loop in VBA will stop at the rounded number
(for example, n = 12.6, the loop stops at 12). So, if the step size of ODE is larger than the
tolerance of the golden section, the two internal points D1 and D2 can be the same and
may lead to a wrong maximum. The second notation is that the ReDim of M(0 to n) gives
the dimension of the nearest integer to n (for example, if n = 12.6, M has 13 columns).
Similarly, the index is rounded to the nearest integer, M(12.6,3) = M(13,3). Con
sequently, using round in Code 10.2 is needed to avoid the error. Since n is rounded,
Applications of ODEs 113
the step in the golden section needs to be larger than delt/2 (to differentiate the values
of f1 and f2).
d 2T
= h ( Ta T ) Eq. 10.1
dx 2
where h is the radiative heat loss parameter (cm-1).
Calculate the temperature profile along the rod.
Solutions
The previous second ODE can be expressed as a system of two first ODEs:
dT
=z Eq. 10.2
dx
dz
= h ( Ta T ) Eq. 10.3
dx
In this problem, we will use two different VBA codes. First, code is developed
to calculate the temperature profile for a given set of initial values (Code 10.3). The
code treats the problem as a system of two first ODEs. The code can provide the
temperature profile at the given heat transfer dz/dx (x = 0).
114 Calculations for Process Engineering Using Excel VBA
Code 10�3� Solving the temperature contribution along a long rod for a
given initial conditions�
Option Base 0
Function temp(t0, z0, Ta, h, dx, xmax)
Dim output(), i, n, dxdt, dzdt
n = xmax/dx: ReDim output(n, 2)
output(0, 0) = 0: output(0, 1) = t0: output(0, 2) = z0
For i = 1 To n
output(i, 0) = output(i–1, 0) + dx
output(i, 1) = output(i–1, 1) + output(i–1, 2) * dx
output(i, 2) = output(i–1, 2) + h * (output(i–1, 1)–Ta) * dx
Next i
temp = output
End Function
The second code (Code 10.4) uses using bisection method to work out the required
slope (z0 or dT/dt at x = 0) so that the temperature at the other end equals 200°C.
The function f in Code 10.4 uses the temp function in 10.3. The output of f is
the difference between the required temperature (200°C) and the predicted value
at x = 10. Using the function bisectionX, one gets a value of 13.413 so that f = 0.
Using this value as input z0, Code 10.3 will give the answer in Table 10.2 and
Figure 10.2.
TABLE 10.2
Temperature Distribution along a Conductive Rod
A B C
1 Distance (m) Temperature (°C) Gradient (°C/m)
2 0 40 13.41394
3 1 53.41394 13.61394
4 2 67.02788 13.94808
4 3 80.97596 14.41836
5 4 95.39433 15.02812
6 5 110.4224 15.78206
7 6 126.2045 16.68629
8 7 142.8908 17.74833
9 8 160.6391 18.97724
10 9 179.6164 20.38363
11 10 200 21.9798
The exact solution for the temperature is given (Chapra and Canale 2010).
The user can compare the numerical solution to this exact solution.
Answer
The program may give an error depending on the value of n, which is decided
by the selected value of dt. For example, if n = 12.51, the array will have
13 rows. Hence, M(n,5) becomes M(13,5). However, the For Next loop stops
at 12.
dX
= k (1 X )
dt
where k is the reaction rate constant, which is dependent on the temperature
é 32, 400 æ 1 1 öù
( )
k = 2.73 ´ 10 4 exp ê ç ÷ú
ë 1.987 è 535 T ø û
where reactor temperature, T, is the function of conversion
T = 515 + 90.1 X
Calculate the residence time and reactor temperature for the conversion of
X = 52%.
Applications of ODEs 117
Hints
VBA code is needed to solve the system of three equations. Although the first equa
tion is an ordinary differential equation, the other two are explicit equations (these
two will be substituted into the ODE). Hence, code for a single ODE can be used.
Furthermore, the code can produce the T and X for plotting (Figure 10.3).
The code can be combined with a bisection method to find time and temperature
when X is 52 %. A bisection code can be used. Hence, the bisection code must eval
uate X at different values of t. It should be noted that each of these evaluations uses
the same calculation from the beginning, t = 0. Consequently, the scanning method
can be used to reduce the calculations.
h
A= ( f (x1 ) + f (x2 ) ) Eq. 11.1
2
where h is the step size (distance between x1 and x2).
Alternatively, the value of the function at the midpoint can be used:
A = hf (( x1 + x2 ) / 2) Eq. 11.2
Eq. 11.2 has an advantage over Eq. 11.1; it requires only one evaluation. The for
mula is more accurate than the simple rectangular method, which only requires f(x1).
Simpson’s rule involves approximating the function by a quadratic polynomial
and integrating this polynomial over two neighbouring elements of the integration.
In addition, Simpson’s rule relies on quadratic interpolation over three points of the
curve, thus requiring an even number of equal-distanced elements.
The area of two elements is given by:
h
A=
6
( f ( x1 ) + 4 f ( x1 + h / 2) + f ( x1 + h ) ) Eq. 11.3
h
A=
8
( f ( x1 ) + 3 f ( x1 + h / 3) + 3 f ( x1 + 2h / 3) + f ( x1 + h ) ) Eq. 11.4
TABLE 11.1
Volumetric Flowrate Data
A B
1 Time (min) Flow (L/min)
2 0 3.5
3 1.8 5.1
4 3.5 5.6
5 6 5.8
6 7 5.9
7 8.2 6.2
8 9.1 6.3
9 10.5 6.1
10 11.6 5.5
11 12 5
Solution
Since the recorded intervals are irregular, we cannot use Simpson’s method. Hence,
the trapezoid method (Eq. 11.1) can be used.
Applying the code to Table 11.1, one can get a final answer of 7.74 L.
Solution
Part A� Space-time is a mathematical concept for flow reactors and is defined as the
ratio between the feed and reactor volume. For example, a space-time of 30 seconds
means the reactor treats one reactor volume of feed every 30 s.
For a plug flow reactor in this question, the space-time, τ, is related to the reaction
rate and concentration of feed by:
X Af 0.5
C Ao
0.5
æ 1+ e A X A ö
t=
10 2 ò
0
ç
è 1 X A ø
÷ dX A Eq. 11.5
Integration 121
where XA is the conversion and εA is the fractional change in the volume of the sys
tem. Since the feed contains 50% inert and the reaction triples the gaseous volume,
εA equals 1. Consequently, Eq. 11.5 becomes:
0.5
C 0.5 XA æ 1+ X A ö
t = Ao2
10 ò
0
ç ÷ dX A
è 1 X A ø
Eq. 11.6
The function inside the integral can be evaluated and plotted for XA between 0 and
100%, as in Figure 11.1. Consequently, the integral in Eq. 11.5 is represented by the
shaded area. The integral can be obtained by VBA code (Code 11.2).
Next i
End Function
Function fXa(Xa)
fXa = ((1 + Xa)/(1–Xa)) ^ 0.5
End Function
In the code, fXa is defined in a separate VBA function. Using the code with n = 8
will return the shaded area as 1.324. Applying Eq. 11.5, τ = 33.1 s. Increasing n will
increase the accuracy of the method.
Part B� In part A, the integration can be obtained numerically for a given Xa.
However, the question requires a value of Xa so that τ = 35s. To get the solution, two
macros are used. The first VBA code is integration, as in Code 11.2. The second one
is applying the Regula Falsi method (Code 11.3). Using these VBA functions, the
conversion for 35s is determined at Xa = 0.824.
Code 11�3� Sizing a plug flow reactor (to be used with the function trapez
in Code 11�2)�
Function PF(Lower, Upper, tau, n)
Dim M, tol, c1, c2, c3, k
c1 = 25 * trapez(0, Lower, n)–tau
c2 = 25 * trapez(0, Upper, n)–tau
M = Lower–c1 * (Upper–Lower)/(c2–c1)
c3 = 25 * trapez(0, M, n)–tau
tol = 10 ^ -7: k = 0
While Abs(c3) > tol And k < 1000
If c1 * c3 < 0 Then
Upper = M: c2 = 25 * trapez(0, Upper, n)–tau
Else
Lower = M: c1 = 25 * trapez(0, Lower, n)–tau
End If
M = Lower + (Upper–Lower) * c1 / (c1–c2)
c3 = 25 * trapez(0, M, n)–tau
k = k + 1
Wend
PF = M
End Function
As in other chapters, the integration can be applied to functions that require com
plicated numerical evaluations. An example is calculating the total heat produced in
the reactors (Chapter 10).
12 Network Analysis
12.1 INTRODUCTION
Network analysis problems are a group of problems dealing with nodes and connec
tions. The problems include the set of nodes and the “weight” factor for each con
nection between two particular nodes. In geographic terms, the nodes can represent
locations, and weights are the distance. Nowadays, the problems seem too simple
with Google Maps and Apple Maps. Yet network problems can be found in more
complex applications besides finding pathways in a city. For example, the weight
factor can be either time or cost in addition to distance. Of course, this kind of opti
misation has puzzled many scientists over the centuries. Perhaps the most celebrated
one is Leonard Euler’s “The Seven Bridges of Königsberg”.
While the network is graphically presented in a map form, the network data (con
nections and weight factors) can be easily stored in an Excel spreadsheet. Conse
quently, VBA code can be routinely employed.
TABLE 12.1
Distance between Points (the Empty Cells Indicating No Connection)
A B C D E F G H J
1 1 2 3 4 5 6 7 8
2 1 6.6 17.5 2.4 2.9 1
3 2 11.6 0.7
4 3 16.7 4.8 11.5
5 4 4 0.8
6 5 0.7 0.2 4
7 6 3 0.2
8 7 0.5
9 8
Please note that the cells represent one-way travel from row to column. Since all
connections are dimensional, the other direction is zero (for example, from B to A).
1 Each node in SSet has a cost value d(i). Initial, SSet contains only SN, and
d(SN) = 0. If node i is not in Sset, Cost(i) = infinity.
2 For each node in FSet, the distances to each node in SSet are obtained.
These values are c(i,j), where i is the node in SSet, and j is the node number
in FSet.
3 The minimum of d(i) + c(i,j) is calculated for node j (MinCost(j)). The cor
responding node in SSet is recorded as PreNode( j).
4 The minimum is determined from all nodes in FSet. Then, the correspond
ing node, jmin, is moved from Fset to Sset.
5 The process stops when jmin is DN.
Once the iteration stops, the shortest pathway and corresponding sequence of
nodes are output.
Network Analysis 125
Solution
First, the input matrix must be checked and filled with two-way connections. The
concept of “infinity” is not available in numerical coding. As a result, a huge but
finite number can be used. The sum of all elements is used to ensure that this number
is larger than all numbers in the matrix (Code 12.1). Here, the Excel function sum
can be used within VBA.
It should be noted that VBA has a conversion function for alphabet and number
(Chr and Asc). However, such a function can be worked within a small range. In
general, one may need another code section to convert the node names into integers.
Code 12�1� Shortest pathway, part 1: setting up matrix M, filling out the
bottom half and all empty cells (no link means infinity distance)�
Option Base 1
Function shortestpath(A, SN, DN)
‘SN is starting node, DS is the destination node
Dim M(), nNode, shortestNNode, N, infinity, i, j, k,
best_j
Dim temp As Variant
Dim Sset(), Fset() As Integer
Dim FCostNode As Variant
Dim MinCost, Prenode, Output, Cost, BestPath As Variant
infinity = 2 * Application.WorksheetFunction.Sum(A)
ReDim M(1 To nNode, 1 To nNode)
For i = 1 To nNode
For j = i + 1 To nNode
126 Calculations for Process Engineering Using Excel VBA
The next section of the code defines the nodes in Sset and Fset. In this case, two
arrays are used (SSet and Fset). Initially, all nodes are in Fset, so Fset(i) = i and
Sset(i) = 0. If a particular node is moved from Fset to Sset, the values of the node in
Fset and Sset are interchanged, Sset(i) = i and Fset(i) = 0.
Code 12�2� Shortest pathway, section 2: sizing SSet and FSet and initial
values
ReDim Sset(1 To nNode): ReDim Fset(1 To nNode)
ReDim FCostNode(1 To nNode): ReDim Cost(1 To nNode)
ReDim MinCost(1 To nNode): ReDim Prenode(1 To nNode)
ReDim BestPath(1 To nNode)
For i = 1 To nNode
Fset(i) = i
Cost(i) = infinity
Next i
Sset(SN) = SN: Fset(SN) = 0: Cost(SN) = 0
In the second section of the code, the matrix sizing is required for the For Next
loop. Initially, all nodes are in Fset with a cost value of infinity. Then node SN is
moved to Sset.
MinCost(j) = (Cost(i) +
M(i, j))
Prenode(j) = i
End If
Next i ‘get the shortest cost to
connect j to a node in S- value is stored at
Prenode and MinCOst
If temp > MinCost(j) Then
temp = MinCost(j)
best _ j = j ‘j moves to the
next value, and may not change best _ j
End If
‘reset cost j for next iteration
End If
Next j ‘after j reaches Nnode, best_j is
identified
‘-------move target j to Sset
Sset(best _ j) = best _ j
Fset(best _ j) = 0
Cost(best _ j) = MinCost(best _ j)
For j = 1 To nNode
If Fset(j) > 0 Then
Cost(j) = infinity
End If
Next j
If best _ j = DN Then
k = nNode
Else
k = k + 1
End If
Loop
In the third section of the code, the best node best_j (gives the shortest distance to
SN) is found and moved from Fset to Sset. The step is repeated until the best node is DN.
Code 12�4� Shortest pathway, part 4: finding the node on the shortest
path backward�
‘find nodes on the shortest path
BestPath(nNode) = DN:
k = nNode
Do While k > 0
BestPath(k–1) = Prenode(BestPath(k))
‘Output(2 + nNode–k, 1) = BestPath(k–1)
128 Calculations for Process Engineering Using Excel VBA
If BestPath(k–1) = SN Then
shortestNNode = (nNode–k + 1)
k = 0
Else
k = k–1
End If
Loop
Since the best path from DN to SN is unknown (the path may not include all of
the nodes in SSet), code is needed to find the nodes and sequence of the shortest path
(Code 12.4). Consequently, the output is exported in Code 12.5.
Code 12�5� Shortest pathway, part 5: exporting the shortest pathway (can
use “set cells” to improve visibility)
ReDim Output(1 To shortestNNode + 6, 1 To 1)
Output(1, 1) = “Shortest Distance”
Output(2, 1) = Cost(DN)
Output(3, 1) = “Number of nodes in the shortest path”
Output(4, 1) = shortestNNode
Output(5, 1) = “Nodes on the shortest path from S to D”
Output(6, 1) = SN
For i = 1 To (shortestNNode)
Output(i + 6, 1) = BestPath(nNode–shortestNNode + i)
Next i
shortestpath = Output
End Function
TABLE 12.2
Answers to the Shortest Distance
Shortest Distance
6
Number of nodes in the shortest path
4
Nodes on the shortest path from S to D
1
8
6
3
Network Analysis 129
Solution
In the beginning, all nodes are included in SSet. Subsequently, node 1 is added to the
travel path and removed from SSet (SSet = 1). After that, the code randomly adds the
remaining nodes to the travel path. In this case, the code needs to generate a random
number for N – 1 times. Each time, a corresponding node from SSet will be added
to the travel path and removed from SSet. At the end of the trial, the total distance is
compared with distancemin. If the trialled distance is smaller than distancemin, then
the distance becomes distancemin and is used to benchmark the subsequent trial.
Otherwise, distancemin remains the same.
Code 12�6� Random search for a short pathway covering all nodes of a
network�
Function shortesttravel(A, kmax)
Dim M(), nl, sel, distance, distancemin, nNode, k _
sol, N, infinity, i, j, k
Dim Sset(), Pathnode() As Integer
Dim Sol() As Variant
‘------
‘using Code 12–1- setting up matrix M, filling out
the bottom half and all empty cells
‘-----
k = 1: distancemin = infinity * nNode
ReDim Sol(1 To nNode + 2)
130 Calculations for Process Engineering Using Excel VBA
The code results in the sequence of nodes, the obtained shortest distance and the
trial number that produced this answer. In case multiple trials obtain the same answer,
the last trial is shown. In the code, kmax is the maximum number of trials. With a
reasonable kmax (around 20000) and some luck, the code can have the shortest cost
of 18.5 with a corresponding sequence of {1,8,6,4,5,7,2,3}. One can also change the
last line to “shortesttravel = M” to see if a correct matrix M is produced.
Answer
Modify Code 12.6 to:
Note that this solution is not always better than the solution from Code 12.6.
Appendices
List of Useful VBA Functions Which Return a Numerical Value
133
134 Appendices
137
Index
Note: Page numbers in italics indicate a figure and page numbers in bold indicate a table on the
corresponding page.
3/8 rule, 119 binary mixture (composition determination),
refractive index (usage), 41
A binary search, 44, 108
bisection method, combination, 48–51
AcC, determination, 57 golden section search, comparison, 51
accumulative flow rate, calculation, 119–120 output change, 52
acetylene production, recycle stream usage, 50
unknowns, presence, 89 Bisection2, 51
usage, 35 bisection code, 26
acosh (spreadsheet function), 15 flowchart, 23, 24
AcR, determination, 57 function value limitation, 25
active spreadsheet, discrete data (storage), 39–40 iterations, number (determination), 30
adaptive_E, 104 removal, 25
adaptive step size, 104 usage, 24, 117
usage, 101–106 bisection method, 20–22, 34, 43
adiabatic flame temperature binary search, combination, 48–51
control, air excess (calculation), 34 Do While loop, usage, 21
determination, example, 31–34 efficiencies, comparison, 30
equation roots, application, 31–34 failures, 26–27
air excess, calculation, 34 false-position method, combination, 40
algorithm, 91 For . . . Next loop, usage, 22
Gauss-Seidel algorithm, coefficient matrix Jacobi method, combination, 75–77
(validation), 74 scanning, usage, 25–26
simplex algorithm, 54–59 usage, 49, 114
anticycling rule (Bland), 56 variable, control error (presence), 22
Apple Maps, usage, 123 bisection/tear analysis, combination, 20
Application.WorksheetFunction.Log, 13–14 BisectionT function, 33
aqueous solution (cooling), microwave heating bisectionX function, usage, 115
(relationship), 80–84 boundary condition, 83
array boundary nodes, 78
definition, 6 boundary value ODEs, 113–116
one-dimensional array, output usage, 41 boundary value problem (BVP), 113
redim, test, 116 branching, incorporation, 4
values, resetting, 7 breakpoints, 17–18
variables, 7
asinh (spreadsheet function), 15 C
atanh (spreadsheet function), 15
ave_4 function, 13 calculated error, 11
average (spreadsheet function), 14 change-of-sign interval, 27, 29
Change spreadsheet cell value, 12–13
B classical fourth-order RK method, 101
ClearContents method, 3
basic variables, 55 coefficient matrix, validation, 74
values, equivalence, 59 cold streams, process, 59
behaviour function, 101–102 Colebrook equation, 27–28, 48–49
best_j (node), 127 friction factor, determination, 23–25
binary adsorption, 86 column.count function, 74
parameters, 87 component flow rates, 36
139
140 Index