Numerical Methods in Chemical Engineering Using Python® and Simulink®-CRC Press (2023)
Numerical Methods in Chemical Engineering Using Python® and Simulink®-CRC Press (2023)
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 mpkbookspermissions@
tandf.co.uk
Trademark notice: Product or corporate names may be trademarks or registered trademarks and are
used only for identification and explanation without intent to infringe.
DOI: 10.1201/9781003360544
Typeset in Times
by codeMantra
Chapter 1 Introduction...........................................................................................1
1.1 Background.................................................................................1
1.1.1 What Is the Numerical Method..................................... 2
1.1.2 Why Are Numerical Methods Necessary..................... 2
1.1.3 When to Use Numerical Methods................................. 3
1.2 Types of Numerical Methods.....................................................3
1.2.1 Direct Method............................................................... 3
1.2.2 Indirect Numerical Methods (Iterative Method)........... 3
1.3 Linear and Nonlinear Systems of Algebraic Equations............. 4
1.3.1 Linear Algebraic Equation............................................4
1.3.2 Nonlinear Algebraic Equations..................................... 7
1.4 Ordinary Differential Equations.............................................. 13
1.4.1 Order of Differential Equation.................................... 14
1.4.2 Analytical Solution of First-Order Differential
Equation...................................................................... 15
1.5 Boundary Value Problems........................................................ 19
1.6 Summary..................................................................................28
1.7 Problems...................................................................................28
Reference............................................................................................. 29
v
vi Contents
2.6 Summary.................................................................................. 70
2.7 Problems................................................................................... 70
Reference............................................................................................. 72
ix
Author
Nayef Ghasem is a professor of chemical engineering at the United Arab Emirates
University. He teaches mainly process modeling and simulation, natural gas process-
ing, and reactor design in chemical engineering, as well as other graduate and under-
graduate courses in chemical engineering. He has published primarily in modeling
and simulation, bifurcation theory, polymer reaction engineering, advanced con-
trol, and CO2 absorption in gas–liquid membrane contactors. He has also authored
Principles of Chemical Engineering Processes (CRC Press, 2012), Modeling and
Simulation of Process Systems (CRC Press, 2019), and Computer Methods in
Chemical Engineering, 2nd Edition (CRC Press, 2021). He is a senior member of
American Institute of Chemical Engineers (AIChE).
xi
1 Introduction
LEARNING OBJECTIVES
1. Realize what a numerical method is.
2. Know when to use numerical methods.
3. Find roots of equations.
4. Identify systems of linear and nonlinear algebraic equations.
5. Detect ordinary differential equations.
6. Identify boundary value problems.
1.1 BACKGROUND
The numerical method is a mathematical implement intended to solve numeri-
cal problems. The numerical method is an approximate computational method for
solving a mathematical problem that is often complex or has no analytic solution.
Numerical methods use computers to solve problems by incremental, repetitive, and
iteration methods, which may be dull or unsolvable by manual calculations. This
chapter intends to give scientists and engineers an overview of numerical methods
of interest.
We can distinguish several distinct stages in the numerical method problem-
solving process. While formulating a mathematical model of a physical system,
engineers must consider that they expect to solve a problem on a computer. It will
therefore provide specific objectives, appropriate input data, adequate checks, and
the type and quantity of output. Once the problem has been formulated, numerical
methods and the initial error analysis must be developed to solve the problem. A
numerical method used to solve a problem is called an algorithm. An algorithm is a
complete set of procedures to solve a mathematical problem. The programmer should
convert the proposed algorithm into a step-by-step instruction for the computer. The
numerical analysts consider all sources of error that might affect the results and how
much precision is required to determine the appropriate step size or the number of
repetitions required.
DOI: 10.1201/9781003360544-1 1
2 Numerical Methods in Chemical Engineering Using Python® and Simulink®
In summary, for the indirect numerical methods, one cannot stop after a certain
number of steps and say that it is good enough because what we will have is an
unfinished problem and no answer, and will need to complete the set of steps to
achieve any answer that makes any sense. By contrast, in the direct numerical meth-
ods, before we begin, we can find out how many steps we need to get to an answer,
and one must complete that number of steps to achieve that answer. Consider solving
the following matrix,
1 2 3
4 5 6
7 8 9
We need to turn these three elements (4,7,8) to zero and then use backward substitu-
tion, and then we will have to solve a system of linear equations; otherwise, it is not
invertible and has no unique solution. However, with iterative numerical methods,
setting the number of steps is not required; stop whenever needed. The longer the
computation period, the more accurate the solution becomes, which offsets computa-
tion time versus accuracy. In conclusion, direct numerical methods use a set number
of steps to achieve a final solution; however, iterative numerical methods use an ini-
tial guess to approximate a final solution.
Ax + By + C = 0 (1.1)
Any equation not written in this form is considered a nonlinear one. The substitution
method we used for linear systems is the same as the one we will use for nonlinear
systems. We solve one equation for one variable and then substitute the result into the
second equation to find another variable, and so on. However, there is a variance in
the possible outcomes. Table 1.1 shows examples of linear and nonlinear equations.
Understanding the difference between linear and nonlinear equations is extremely
important. Table 1.2 shows linear and nonlinear equations.
TABLE 1.1
Examples of Linear and Nonlinear Equations
Linear Equations Nonlinear Equations
y = 8x − 9 y = x2 − 7
y + 3x = 1 y+x=6
y+ x = 7 y2 − x = 9
TABLE 1.2
Differences between Linear and Nonlinear Equations
Linear Equations Nonlinear Equations
The equation has a maximum order of one degree. The equation has the maximum degrees of two or
more.
A straight line is formed on the graph. The equation forms a curve on the graph.
The general form of linear equation is y = mx + c The general form of nonlinear equations is
where x any y are the variables, m is the slope of ax 2 + by 2 = c where x and y are the variables and
the line, and c is a constant value. a, b, and c are the constant values.
is linear, you may ask what it would mean to solve a system of linear equations.
Accordingly, solving a system of linear equations essentially means finding and thus
assigning a value to each of your unknown variables because there is sometimes more
than one solution to a system of linear equations. The total set of solutions that can
solve our system of linear equations is called the solution set. In general, a linear alge-
braic equation (LAE) is one in which the highest power of the variables is always 1.
The standard form of a LAE is one variable of the form
ax + b = 0 (1.2)
where a and b are constants and x is a variable, a is a coefficient of the variable x, and
b is a constant. A system of linear equations is a collection of more than one equa-
tion. The linear equation is an algebraic equation where each term has an exponent
of 1, and when this equation is plotted, it always results in a straight line; that is why
it is called a ‘linear equation’. There are linear equations in one variable and linear
equations in two variables. Let us learn how to define linear and nonlinear equations
with the help of the following examples. To solve the system of linear equations, the
minimum number of unknowns should be equal to or less than the number of equa-
tions we have. If the number of unknowns is more than the number of independent
equations, then we cannot solve the system of equations.
Solution
2x = 8 − 3
8−3
x= = 2.5
2
3 x + 6 = 18
Solution
To solve the given equation, we put the numbers on the right side of the equation
and keep the variable on the left side. This means:
3 x = 18 − 6
3 x = 12
12
x= =4
3
The sum of the two numbers is 44. Find the numbers by forming a linear equation
if one number is ten times more than the other.
Solution
x + ( x + 10 ) = 44
Introduction 7
The result is
2 x = 44 − 10
2 x = 34
x 3 + 2 x 2 −9 = 0 (1.3)
3 x + 6 y = 12
5x − 8 y = 2
Solution
3 x = 12 − 6 y →→ x = 4 − 2 y
5( 4 − 2 y) − 8 y = 2
Simplify
20 − 10y − 8 y = 2
Rearrange
18y = 18
8 Numerical Methods in Chemical Engineering Using Python® and Simulink®
3x + 6 (1) = 12
Hence: x = 2
3 x − y = −2
2x 2 − y = 0
Solution
Rearrange y as a function of x
y = 3x + 2
2 x 2 − 3x − 2 = 0
The value of x
− b ∓ b 2 − 4ac 3 ∓ 3 − ( 4 )( 2 )( −2 ) 3 ∓ 25
2
x= = =
2a ( 2 )( 2 ) 4
1 1
x = − , 2 , y = , 8
2 2
The hydrolysis of acetic anhydride forms acetic acid took place in a continuously
stirred tank reactor (V = 1250 L). The species concentration of feed to the reactor is
2.5 mol/L of acetic anhydride and 50 mol/L of water. The feed flow rate is 15 L/s
(Figure 1.1). The reaction
( CH3CO )2 O + H 2O ↔ 2CH3COOH
The reaction rate is first in acetic anhydride and first in the water. The reaction rate
constant is 0.075 L/(mol s). Derive the nonlinear equations.
Introduction 9
Solution
( CH3CO )2 O + H 2O ↔ 2CH3COOH
A + W = 2B
rA = − kC ACW
FAo − FA + RAV = 0
FAo − FA + RAV = 0
L L mol mol
v0 = 15 , k = 0.0025 , V = 1250 L, C Ao = 2.5 , Cwo = 50
s ( mol s ) L L
10 Numerical Methods in Chemical Engineering Using Python® and Simulink®
After the substitution of the known data, there are two unknown variables (C A , CW )
and two equations. The unknown can be found by the substitution method.
15 L 2.5 mol − 15 L C L
s A − 0.0075 C ACW (1250 L ) = 0
L s mol s
L mol L L
15
s
50 − 15 CW − 0.0075 C ACW (1250 L ) = 0
L s mol s
mol
2.5 − C A − ( 29.6875)C ACW = 0
L
mol
50 − CW − ( 29.6875) C ACW = 0
L
C A − CW + 47.5 = 0
CW = C A + 47.5
mol
2.5 − C A − ( 0.625)C A (C A + 47.5) = 0
L
Simplify
Simplify further
mol
C A = 0.081
L
mol
Cw = 47.6
L
Introduction 11
The elementary gas phase reaction occurs in a plug flow reactor (PFR) at constant
temperature and pressure.
A + B → 2C
The total inlet concentration is 0.5 mol/L. The feed is equal molar in A and B. The
inlet molar rate of A is 5.0 mol/s. The reaction rate constant is k = 0.1 L/mol/s. Find
the volume of the PFR to achieve 90% conversion of A.
Solution
This is a reactor design example where the design equation of the PFR for the gas
phase is to be used.
0.9
dx
V = FAo
∫ −r
0
A
−rA = kC AC B
FA
CA =
v
where FA is the molar flow rate of A, v is the volumetric flow rate. For gas phase,
P T
v = v0 (1 + ε x ) 0
P To
FA
= FA 0 (1 − x )
CA = v = C Ao (1 − x )
v0 (1 + 0 )
−rA = kC A2 0 (1 − x )
2
Analytical integration,
x1
dx x1
∫ (1 − x )
0
2 =
1 − x1
The integral can also be found using numerical integration techniques in later
chapters.
A+ B→C
Occurs in 1 m 3 continuous stirred tank reactor (CSTR) reactor. The rate law of this
reaction is rA = − kC A , if k = s −1, C Ao = 0.02 mol/L in an inert. The inlet volumetric
flow rate is 10.0 L/s.
What is the conversion of A under steady-state conditions at 350°K and 5 atm?
The ideal gas law R = 0.0821 L·atm/mol/K.
Solution
The question is a reactor design problem, where the single pass conversion of a
liquid phase reaction in a CSTR reactor is required (required knowledge in reactor
design).
FAo X
VCSTR =
−rA
The rate of reaction is first order, the liquid concentration of A in terms of x
C A = C Ao (1 − X )
Combining
( FAo X )
VCSTR =
kC Ao (1− X )
Rearranging to solve for X
liter
1 m 3 1000 3 × 0.005 s −1
m X
=
liter 1− X
10
s
Simplifying
liter
1 m 3 1000 3 × 0.005 s −1
m X
= 0.5 =
liter 1− X
10
s
Solving for X
0.5 1
X= =
1.5 3
dy
= 6x + 1 (1.4)
dx
dy 3
+ y = x2 (1.5)
dx x
d3y
= 64 x (1.6)
dx 3
d2y dy
− 2 − 3y = 0 (1.7)
dx 2 dx
14 Numerical Methods in Chemical Engineering Using Python® and Simulink®
dy
+ 2 y = sin x (1.8)
dx
2
dy = 4x (1.9)
dx
Second order:
d2y
+ 4xy = e x (1.10)
dx 2
Third order:
d3y d2y dy
3 −6 +9 =0 (1.11)
dx dx 2 dx
Consider the following simple series of reactions taking place in a batch reactor
k1
A→ B
k2
B→C
Assuming that the reaction rate is first order concerning A and B, derive the con-
centration change of components A, B, and C with time.
r1 = k1C A
r2 = k 2C B
Solution
The complete set of differential equations for a well-mixed batch reactor are as
follows:
dC A
= −r1 = − k1C A
dt
dC B
= r1 − r2 = k1C A − k 2C B
dt
dCc
= r3 = k 2C B
dt
Introduction 15
dy
=5 y (1.12)
dx
The exact solution can be found as follows:
Rearrange the equation as follows
dy
= 5dx (1.13)
y
Integrating
ln ( y ) = 5 x (1.14)
y = e5x (1.15)
dy
= 2x (1.16)
dx
is
y = x2 + c (1.17)
dy
= 2x , y (1) = 4 (1.18)
dx
is
y = x2 + c (1.19)
4 = (1) + c
2
(1.20)
16 Numerical Methods in Chemical Engineering Using Python® and Simulink®
y = x2 + 3 (1.21)
A liquid level system where liquid enters a cylindrical tank at the rate of Ff and
leaves at a rate Fo . The mathematical model for the system is a differential equa-
tion that shows the relationship between the height (h) of the liquid and the input
flow rate. The surface area of the bottom of the cylindrical tank is A (Figure 1.2).
Develop the differential equation.
Solution
dm
= m. f − m. o
dt
In terms of flow rate, assuming constant density,
d ( ρV )
= ρ Ff − ρ Fo
dt
Simplify and replace V with Ah. The following ODE is generated:
dh
A = Ff − Fo
dt
Purified water flows into a tank at a rate of 10 L/min. The contents of the tank are
well mixed; they flow out at a rate of 10 L/min. Add salt to the tank at the rate of
0.1 kg/min. Initially, the tank contains 10 kg of salt in 100 L of water. The volume of
the tank is 100 L. How much salt is in the tank after 30 minutes?
Solution
Here, the setup is very similar to the previous example. The only difference from
the previous one is adding 0.1 kg/min salt to the tank. As a result, we can modify
the differential equation to consider this. Let the concentration of salt in the tank, Cs
Total material balance,
d (VCs )
= 0 + 0.1− Cs Ff
dt
Simplify
dCs kg kg liter
(100 liter ) = 0.1 − Cs × 10
dt min liter min
Rearrange
dCs
= 0.001 − 0.1Cs
dt
The initial condition is at time = 0, and the concentration of salt is
10 kg salt kg
Cs ( 0 ) = = 0.1
100 liter water liter
Integrating the generated to ODE
kg
Cs ( t ) = 0.01448
liter
The amount of salt
kg
ms = 100 liter × Cs ( 30 ) = 0.01448 × 100 liter = 1.448 kg
liter
18 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Pure water flows into a tank at 12 L/min. The tank’s contents are thoroughly mixed
and flow out at 10.0 L/min. Initially, the tank contains 10 kg of salt in 100 L of water.
Develop the model ODE equation and then calculate the amount of salt in the
tank after 30 min.
Solution
The inlet flow rate is greater than the outflow rate. As a result, size is not constant.
Using the initial conditions and flow rates, we can say that the volume V of liquid
in the tank is
d (CsV )
= Ff ( 0 ) − FoCs
dt
Since the volume varied with time
dCs dV
V + Cs = −FoCs
dt dt
Overall mass balance at constant density
dV
= Ff − Fo
dt
Replace dV /dt with Ff − Fo
dCs
V + Cs ( Ff − Fo ) = − FoCs
dt
Rearrange
dCs
(Vo + vot ) = − FoCs − Cs Ff + FoCs
dt
Simplify further
dCs
(Vo + vot ) = −Cs Ff
dt
Rearrange
dCs dt
= −Ff
Cs ( o o )
V + v t
Using separable integration
F V
ln (Cs ) = − f ln o + t + C1
vo vo
Introduction 19
12 100
ln ( 0.1) = − ln + 0 + C1
2 2
C1 = 21.169
F V
ln (Cs ) = − f ln o + t + 21.169
vo vo
12 100
ln (Cs ) = − ln + 30 + 21.169
2 2
kg
Cs = 0.00596
liter
The amount of salt in 30 min
kg
Cs = 0.00596 × 100 liter = 0.596 kg
liter
1 d 2 dc
D 2 r = R (1.22)
r dr dr
with the following boundary condition
20 Numerical Methods in Chemical Engineering Using Python® and Simulink®
dc
at r = 0, = 0 (Axial symmetry about the origin)
dr
at r = rp , c = c As (Concentration at the catalyst surface)
A → B, rA = − kC A
C A is the local molar concentration of A in the catalyst, and k is the first-order rate
constant. Considering molecular diffusion and neglecting bulk diffusion. Assuming
isothermal operation, the A concentration at the catalyst’s surface is constant and
equal to C AS . The following differential equation governs the steady-state equation
mass balance on cylindrical coordinates considering the given assumptions
1 d dC A
rD − kC A = 0 (1.23)
r dr dr
Introduction 21
dC A
at r = 0, =0 (1.24)
dr
Heat transfer is an essential subject in engineering. Fins are frequently used in heat-
ing houses, cars, and industry.
Figure 1.5 shows a fin used in heat transfer to increase the surface area available
for heat transfer between metal walls and poorly conductive fluids such as gases.
A simple and practical application of thermal conductivity is a calculation-efficient
cooling fin. Assuming L >> B, the fin will not lose heat from the end of the edges;
the heat flows to the surface by the temperature profile in the fin. In which h is the
constant convective heat transfer coefficient as is the surrounding fluid temperature
Ta , then the governing differential equation is
d 2T hA h ( 2W L ) h
k 2 = ( T − Ta ) = ( T − Ta ) = ( T − Ta ) (1.25)
dz V 2BWL B
where k is the thermal conductivity of the fin, and the boundary conditions are
at z = 0, T ( 0 ) = Tw
d2y
− y = 0; y ( 0 ) = 0, y (1) = 1
dx 2
Consider a general solution to the differential equation
y ( x ) = c1e x + c2e − x
22 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Solution
m 2 − 1 = 0, m∓ = ∓1
y ( x ) = c1e x + c2e x
y ( 0 ) = 0 = c1e 0 + c2e −0 = c1 + c2
Simplifying,
0 = c1 + c2
Simplify
c2
1 = c1e +
e
Substitute c1 = −c2
c2
1 = −c2e +
e
Rearrange
Introduction 23
1 1 − e2
1 = c2 − e = c2
e e
e
c2 =
1− e 2
Then
−e
c1 = −c2 =
1− e 2
−e x e − x
y ( x ) = e + e
1 − e 2 1 − e 2
d2y dy π
+ 4 y = 0, y ( 0 ) = 1, = 2
dx 2 dx 2
If the general solution of the differential equation is
y ( x ) = c1 cos ( 2 x ) + c2 sin ( 2 x )
Solution
p ( m ) = m 2 + 4 = 0 → m∓ = ∓2i
y ( x ) = c1 cos ( 2 x ) + c2sin ( 2 x )
y ( 0 ) = 1 = c1 cos ( 0 ) + c2 sin ( 0 )
Hence,
1 = c1 + 0 => c1 = 1
24 Numerical Methods in Chemical Engineering Using Python® and Simulink®
π π π
y′ = 2 = −2c1 sin 2 × + 2c2 cos 2 ×
2 2 2
Simplify
π
y′ = 2 = −2c1 sin ( π ) + 2c2 cos ( π ) = 0 − 2c2
2
Accordingly,
c2 = −1
Substitution of c1 and c2
Develop the unsteady state BVP model equation for the diffusion of a laminar flow
liquid solute A into water. Starting with the following equation of change,
∂C A
+ vz .∇C A = D∇ 2C A + r
∂t
Solution
FIGURE 1.6 Schematic of the unsteady state mass transfer in a tubular liquid flow.
Introduction 25
1. Steady-state operation.
2. No reaction (r = 0).
3. Neglect the diffusion in the radial direction.
4. Neglect velocity in the r-direction.
5. Laminar flow ( N Re < 2100) , the parabolic velocity profile.
r
2
vz = 2 vo 1 −
R
∂C A
+ vz .∇C A = D∇ 2C A + rA
∂t
Expand the equation
∂C A r ∂C A
2
∂C A ∂ 2 C A 1 ∂ ∂C A
+ 2 vo 1 − + vr = D + r + rA
∂t R ∂z ∂r ∂z 2 r ∂z ∂r
Initial conditions
t = 0, C A = 0
Boundary conditions
z=0 C A = C Ao
∂C A
z = L, =0
∂z
Symmetric condition at the center
∂C A
r = 0, =0
∂r
Non-reactive wall
∂C A
r = R, − =0
∂r
The equation can be simplified based on the given assumption
r ∂C A
2
∂2 C A
0 + 2 vo 1 − + 0 = D 2 + 0
R ∂z ∂z
26 Numerical Methods in Chemical Engineering Using Python® and Simulink®
r 2 ∂C A ∂2 C A
2 vo 1 − 2 −D =0
R ∂z ∂z 2
∂v ∂v v ∂v ∂v ∂P 1 ∂ ∂vz 1 ∂ 2 vz ∂ 2 vz
ρ z + vr z + θ z + v z z = − + µ r + + 2 + ρ gz
∂t ∂r r ∂θ ∂z ∂z r ∂r ∂r r 2 ∂θ 2 ∂z
It is better to use cylindrical coordinates here and velocity in the z-direction only.
The continuity equation is equivalent to the following, assuming constant ρ and
µ . The ρg is not necessary because gravity does not play a role. The schematic
diagram is shown in Figure 1.7.
Solution
∂P 1 ∂ ∂vz
= µ r
∂z r ∂r ∂r
Since the pressure gradient is linear
PL − Po d dvz
r= r
µL dr dr
dvz P − Po r 2 c1
= − L +
dr 2 µ L r r
P − Po 2
vz = − L r − c1lnr + c2
4 µ L
Boundary conditions 1
dv
at r = 0, z = 0
dr
Applying boundary condition 1 in the following equation,
dvz P − Po r 2 c1
= − L +
dr 2 µ L r r
P − Po 0 c1
0 = − L +
2 µ L r r
Accordingly,
c1 = 0
PL − Po 2
R = c2
4µ L
Substitution of c1 and c2
P − Po 2 PL − Po 2
vz = − L r + R
4 µ L 4µ L
Rearrange
P − Po 2 2
vz = L
4 µ L
(
R −r )
Reposition again
P − Po 2 r 2
vz = L R −1
4 µ L R
or
( Po − PL ) R 2 r
2
vz = 1−
4µ L R
28 Numerical Methods in Chemical Engineering Using Python® and Simulink®
1.6 SUMMARY
Numerical methods is a discipline in mathematics concerned with the development
of effective methods for obtaining numerical solutions to mathematical problems that
are difficult to solve by analytical methods. This chapter deals with possible equa-
tions that may appear in many topics of chemistry or other engineering subjects that
need to be solved by numerical methods. Linear and nonlinear algebraic equations
may appear in material and energy balances, mass transfer, heat transfer, and ordi-
nary and partial differential equality in modeling and simulation.
1.7 PROBLEMS
x + 7 = 12
2x + y = 6
x+y=4
Find the value of x, y
Answer: (x = 2, y = 2)
3. A system of nonlinear equations consists of two or more equations with at
least one equation that is not linear
x 2 + y 2 = 25
3x + 4 y = 0
Find the value of x, y
Answer: (x = 4, y = –3)
4. Solve the system of two nonlinear equations
x 2 + y 2 = 45
x 2 − y 2 = −27
Find the value of x, y
Answer: ( x = 3, y = 6)
5. Pure water flows into a tank at a rate of 10 L/min. The contents of the tank
are preserved and mixed well. The contents flow out at a rate of 10 L/min.
Initially, the tank contained 10 kg of salt in 100 L of water. How much salt
will there be in the tank after 30 minutes?
Answer: 0.5
Introduction 29
Answer: 0.0248
7. Water with salt dissolved at a specified concentration of 0.1 kg/L, flowing
into a tank at a rate of 10 L/min. The contents of the tank are well mixed,
and the contents flow out at a rate of 10 L/min. Initially, the tank contained
10 kg of salt in 100 L of water. How much salt will there be in the tank after
30 minutes?
Answer: 0.0248
8. Water with salt dissolved at a specified concentration of 0.1 kg/L, flowing
into a tank at a rate of 10 L/min. The contents of the tank are well mixed,
and the contents flow out at 12 L/min. Initially, the tank contained 10 kg
of salt in 100 L of water. How much salt will there be in the tank after 30
minutes?
Answer: 0.099
9. Write the ODE of the following two simple series reactions taking place in
a batch reactor
k1 k2
A→ B→ C
Write the complete set of the differential equation for a well-mixed batch
reactor.
d2y
+ 2 y = 0, y ( 0 ) = 1, y (π ) = 1
dx 2
Answer:
( 2t ) − sin (( 2t )) sin ( 2t )
cos 2t
y = cos
REFERENCE
1. Ghasem, N., 2019. Modeling and Simulation of Chemical Process Systems, New York:
CRC Press.
2 Numerical Solutions
of Linear Systems
Numerical methods can solve systems of linear equations. Generally, they are divided
into two categories: direct methods, which lead to the exact solution within a limited
number of steps, such as the Gaussian elimination method, and indirect methods.
Indirect methods (iterative methods) are valuable for problems involving massive
private arrays, such as Jacobi and Gauss-Seidel. This chapter focuses on linear alge-
braic equations and how to solve them using different methods such as Cramer’s rule,
Gauss elimination method, and Gauss-Jordan, Jacobi, and Gauss-Seidel elimination
methods.
LEARNING OBJECTIVES
1. Identify the linear algebraic equation.
2. Find the determinant of 2 × 2 and 3 × 3 matrices.
3. Use Cramer’s rule to solve systems of two and three equations.
4. Use Gauss and Gauss-Jordan elimination methods.
5. Apply Jacobi and Gauss-Seidel iterative methods.
6. Make use of Simulink and Python to solve linear algebraic equations.
2.1 INTRODUCTION
A system of linear equations is a collection of linear equations that are independent
of one another, and we cannot derive one equation from another. An equation is lin-
ear if each term is simply a constant or a constant multiplied by a variable. If we ever
have a variable multiplied by another variable or a variable to the power of anything,
then the equation is not linear. Solving a system of linear equations means finding a
value for each unknown variable. There is sometimes more than one solution to a set
of linear equations; the complete set of solutions is called the solution set.
The linear system of equations ax = b can be solved using various numerical
methods. A numerical method is a mathematical tool designed to solve numerical
problems in natural and social sciences, engineering, medicine, and business. The
following sections explain the system of linear algebraic equations and the appropri-
ate methods for numerical solutions [1].
DOI: 10.1201/9781003360544-2 31
32 Numerical Methods in Chemical Engineering Using Python® and Simulink®
A linear algebraic equation is one in which the highest power of the variables is
always 1. The standard form of a linear algebraic equation is one variable of the form
ax + b = 0
a21X1 + a22 X 2 + … + a2 n X n = b2
am1X1 + an 2 X 2 + … + amn X n = bm
where m is the number of rows and n is the number of columns. Here m is the number
of independent equations to solve n number of variables. In a matrix structure,
AX = b
X1
The X matrix is X 2
Xn
b1
The b matrix is b2
bm
In general, a matrix has 𝑛 × 𝑚 elements. If n = m, there may be a unique solution,
and the rank of the matrix is m. Consider the following matrix, A
The determinant, A
A = ad − bc
2x + 3y = 5
x−y=4
Numerical Solutions of Linear Systems 33
2 3 x 5
A= ,X = ,b=
1 −1 y 4
2 x + 3 y + 2z = 7
x+ y−z =5
3x + 3 y − 2z = 4
2 3 2
A= 1 1 −1
3 3 −2
x 7
X = y , b = 5
z 4
5 1
3 2 × −3 0
1 0 2× 2
0 3 3× 2
5 1
3 2 × 1 2 3
4 5 6 2×3
0 3 3× 2
0
1
2 3 × 5
1× 3
4 3×1
5 1 1 2
3 2 × 4 5
0 3 3× 2 8 7 3× 2
5 1 0 1 3
3 2 × 4 5 6
0 3 3× 2 7 8 9 3×3
1
3 ×
1 2
1× 3
2 2×1
k
Rule Cij = ∑a
1
ik × bkj
5 ( 5 × 3 + 1 × 1) ( 5 × 0 + 1 × 5)
1
3 × 3 0
2 1 = ( 3 × 3 + 2 × 1) ( 3 × 0 + 2 × 5)
5 2× 2
0 3 3× 2 ( 0 × 0 + 3 × 1) ( 0 × 0 + 3 × 5)
3× 2
I = [ A ]m× n × [ A ]n× m
−1
Numerical Solutions of Linear Systems 35
1 0 0
I ≡ 0 1 0
0 0 1
a11 a12
A=
a21 a22
1 a22 − a12
[ A]−1 =
A −a21 a11
where the value of A should not be equal to zero; otherwise, the matrix A is con-
sidered singular.
The transpose matrix [ A ] is the interchange of rows with columns, as shown below:
T
a1
a
[ A] = 2
...
a
n n×1
36 Numerical Methods in Chemical Engineering Using Python® and Simulink®
[ A]T = a1 a2 … an
1×n
[ A][ X ] = [ b ]
Aj
Xj =
A
ax + by = e
cx + dy = f
If we solve for x, the x column is replaced with the column of constants (e, f) on the
right-hand side of the equations. Using Cramer’s rule, the solution for x is given as
follows in which D ≠ 0:
e b
f d ed − fb
Dx =
x= =
D a b ad − cb
c d
a e
c f af − ce
D
y= y = =
D a b ad − cb
c
d
Numerical Solutions of Linear Systems 37
a1x + b1 y + c1z = d1
a2 x + b2 y + c2 z = d 2
a3 x + b3 y + c3 z = d3
The solution is
Dx D D
x= , y = y , z = z , where D ≠ 0
D D D
a1 b1 c1
D = a2 b2 c2 , D ≠ 0
a3 b3 c3
Then,
d1 b1 c1 a1 d1 c1 a1 b1 d1
Dx = d2 b2 c2 , Dy = a2 d2 c2 , Dz = a2 b2 d2
d3 b3 c3 a3 d3 c3 a3 b3 d3
The equations should be independent, and the determinant should not equal zero. For
example, the following two equations are not independent.
2 x1 + 3 x 2 = 11
4x1 + 6 x 2 = 22
2 3
A= = 2×6−3× 4 = 0
4 6 2× 2
Accordingly, the two equations are not independent. There is no unique solution, and
the matrix coefficient is singular; a zero determinant means that either the system has
no solution or an infinite number of solutions.
38 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Solve the following two linear algebraic equations manually using Cramer’s rule.
2 x1 + 3 x 2 = 11
x1 + x 2 = 4
Verify the manual calculation with Simulink and Python programming of Cramer’s
rule.
Solution
First, we must check the singularity of the equation by finding the determinant.
Put the equations into matrix format.
2 3 11
A= , b = 4
1 1
The determinant of A,
A = ( 2 × 1) − ( 3 × 1) = −1
The two algebraic equations are independent, and there is a unique solution. To
find the unknown values, use Cramer’s rule:
11 3
Ax = = 11 − 12 = −1
4 1
2 11
Ay = = 8 − 11 = −3
1 4
Accordingly,
Ax 1
x1 = =− =1
A −1
Ay −3
x2 = = =3
A −1
Two ways can solve the two independent equations using Simulink’s ‘Algebraic
Constraint’ block (Figure 2.1a). Figure 2.1a is to write each equation using the avail-
able blocks in Simulink (Gain, Constant, and Sum). By contrast, in Figure 2.1b, the
matrix coefficients entered the Gain in a vector structure ‘[2 3;1 1]’ and selected
Numerical Solutions of Linear Systems 39
Figure 2.2 shows the Simulink solution using Cramer’s rule in the form of a
MATLAB function embedded in the Simulink MATLAB function block available in
the Simulink library under user-defined functions.
FIGURE 2.1 Simulink solution uses the Simulink algebraic constraint function block to
solve the equation defined in Example 2.1.
FIGURE 2.2 Simulink solution using Cramer’s rule embedded in the MATLAB function to
solve the equations stated in Example 2.1.
40 Numerical Methods in Chemical Engineering Using Python® and Simulink®
The following program is the MATLAB code describing Cramer’s rule embed-
ded into the MATLAB function.
Python Solution
The following program is the Python code that employs Cramer’s rule to solve the
two algebraic equations presented in Example 2.1.
# Example 2.1
# Calculating the determinant
from sympy import *
x1,x2 = symbols([‘x1’,‘x2’])
system = [Eq(2*x1 + 3*x2,11),
Eq(x1 + x2,4)]
soln = solve(system,[x1,x2])
print(‘\n the solution:’,soln)
The following are the Python program executed results of Example 2.1.
The solution: {x1: 1, x2: 3}
0 2 1
A= 3 −1 1
4 0 1
To find the determinant of the 3 × 3 matrix, first, take the first element of the first
row and multiply it by a secondary 2 × 2 matrix, which becomes from the elements
remaining in the 3 × 3 matrix that do not belong to the row or column to which
your first selected elements belong. Arrange the matrix with the first two columns
and then follow the formula.
0 2 1
A= 3 −1 1
4 0 1
Accordingly,
Numerical Solutions of Linear Systems 41
−1 1 3 1 3 −1
A = (0) − ( 2) + (1)
0 1 4 1 4 0
Simplify
A = 0+2+4 = 6
Simulink Solution
The Simulink solution of Example 2.2 is shown in Figure 2.3, followed by the
embedded MATLAB code implanted in the MATLAB function.
The following program is the MATLAB code embedded in the MATLAB
function.
Python Solution
#Example 2.2
#Calculating the determinant
#importing Numpy package
import numpy as np
FIGURE 2.3 Simulink’s solution using a MATLAB function implanted with MATLAB
code to find the determinant of the matrix given in Example 2.2.
42 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Execution
Determinant of given 3 × 3 square matrix: 6
Find the determinant of the following 3 × 3 matrix manually and using Simulink and
Python programming.
1 −3 7
A= 1 1 1
1 −2 3
Solution
The determinant is a scalar value equal to the product of the main diagonal ele-
ments minus the product of its counter diagonal elements. The determinant of A
1 −3 7
A= 1 1 1
1 −2 3
Split the matrix as follows:
1 1 1 1 1 1
A = +1 − ( −3) + 1 +7
−2 3 1 3 1 −2
A = 1( 3 + 2 ) + 3( 3 − 1) + 7 ( −2 − 1) = 5 + 6 − 21 = −10
Simulink Solution
Figure 2.4 displays the value of the matrix determinant listed in Example 2.3, solved
by Simulink, shown in the embedded MATLAB function.
The embedded MATLAB code is implanted into the MATLAB function to find
the determinant of the matrix defined in Example 2.3.
Res = a_det;
Numerical Solutions of Linear Systems 43
FIGURE 2.4 Simulink’s solution using the MATLAB function implanted with MATLAB
code to find the determinant of the matrix given in Example 2.3.
Python Solution
The Python code for the determinant of the 3 × 3 matrix is programmed below. It
can solve any 3 × 3 matrix by modifying the array coefficients.
# Example 2.3
#importing Numpy package
import numpy as np
# creating a 3X3 Numpy matrix
n_array = np.array([[1,-3,7],
[1,1,1],
[1,-2,3]])
Execution
Determinant of given 3 X 3 square matrix: -10
Use Cramer’s rule to solve the set of the following linear equation manually.
x+ y−z = 6
3 x − 2 y + z = −5
x + 3 y − 2 z = 14
Solution
Cramer’s rule is a method that uses determinants to solve systems of equations that
have the same number of equations as variables. First, put the equation in matrix
format.
1 1 −1 6
D = 3 −2 1 , d = −5
1 3 −2 14
Then, to solve for x, replace the first column with the d column (the constants at
the right-hand side of the three equations).
6 1 −1
Dx = −5 −2 1
14 3 −2
1 6 −1
Dy = 3 −5 1
1 14 −2
Replace the third column with the d column.
1 1 6
Dz = 3 −2 −5
1 3 14
1 1 −1
D= 3 −2 1
1 3 −2
Split the matrix.
−2 1 3 1 3 −2
D = + (1) − (1) + ( −1)
3 −2 1 −2 1 3
D = 1 + 7 − 11 = −3
Augment the matrix with the first two columns and then follow the formula.
6 1 −1
Dx = −5 −2 1
14 3 −2
Numerical Solutions of Linear Systems 45
Solving for Dx
Dx = 6 ( −2 )( −2 ) − ( 3)(1) − 1 ( −5)( −2 ) − (14 )(1) − 1 ( −5)( 3) − (14 )( −2 )
Dx = 6 + 4 − 13 = −3
Augment the matrix with the first two columns and then follow the formula.
1 6 −1
Dy = 3 −5 1
1 14 −2
Solving for Dy
Dy = 1 ( −5)( −2 ) − (14 )(1) − 6 ( 3)( −2 ) − (1)(1) − 1 ( 3)(14 ) − (1)( −5)
= −4 + 42 − 47 = −9
Solving for Dz
1 1 6
Dz = 3 −2 −5
1 3 14
Augment the matrix with the first two columns and then follow the formula.
1 1 6
Dz = 3 −2 −5
1 3 14
Dz = 6
Solve for x.
Dx −3
x= = =1
D −3
Solve for y.
Dy −9
y= = =3
D −3
Solve for z.
Dz 6
z= = = −2
D −3
46 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 2.5 Simulink block diagram (a) detailed solution (b) using the gain and constants
in matrix format to solve the set of equations presented in Example 2.4.
Simulink Solution
We are solving the set of linear equations using Simulink and the Algebraic con-
straint’s function built in the Simulink library. The problem can be solved in two
ways: The first method is constructing each algebraic equation using the basic
Simulink block diagram using the primary Algebraic constraint function (Figure 2.5a).
The second method puts the matrix coefficients in the Gain and the constants of the
algebraic equation in the Simulink Constant block, as shown in Figure 2.5b.
In linear algebra, Cramer’s Rule is an explicit formula for solving a system of lin-
ear equations with as many equations as unknowns. The rule is valid whenever
the system has a unique solution. It expresses the solution in terms of the coef-
ficient matrix’s determinants and matrices obtained from it by replacing one col-
umn with the vector of the right-hand sides of the equations. Figure 2.6 shows the
Simulink solution of Example 2.4 using Cramer’s Rule. The figure is followed by the
MATLAB code that embeds the Simulink function.
FIGURE 2.6 Simulink block diagram using Cramer’s rule encoded in MATLAB and
implanted in a MATLAB function indicating the solution to the set of equations defined in
Example 2.4.
Python Solution
The following Python code determines the solution of the three linear algebraic
equations presented in Example 2.4, followed by the execution results. The pro-
gram can be used to solve any valid system of three algebraic equations by replac-
ing the matric coefficients (a).
# Example 2.4
import numpy as np
a = np.array([[1,1,-1],
[3,-2,1],
[1,3,-2]])
b = np.array([6,-5,14])
def cramer(mat,constant):
D = np.linalg.det(mat)
mat1 = np.array([constant,mat[:,1],mat[:,2]])
mat2 = np.array([mat[:,0],constant,mat[:,2]])
mat3 = np.array([mat[:,0],mat[:,1],constant])
Dx = np.linalg.det([mat1,mat2,mat3])
X = Dx/D
print(‘\n The result,x,y,z’)
print(X)
cramer(a,b)
Execution result
The result,x,y,z
[ 1.3.-2.]
48 Numerical Methods in Chemical Engineering Using Python® and Simulink®
12x + 3 y = 15
2 x − 3 y = 13
Confirm the manual calculation with Simulink and Python programming of
Cramer’s rule.
Solution
12 3 x 15
A= , X = y , B =
2 −3 13
15 3
D 13 −3
x= x =
D 12 3
2 −3
Dx −45 − 39
x= = =2
D −36 − 6
12 15
D 2 13
y= x =
D 12 3
2 −3
Dx 156 − 30
y= = = −3
D −36 − 6
Simulink Solution
Figure 2.7 describes the Simulink solution of the two linear algebraic equations
defined in Example 2.5. The MATLAB embedded code follows the figure.
FIGURE 2.7 Simulink block diagram using Cramer’s rule encoded in MATLAB and
implanted in a MATLAB function representing the solution to the equations defined in
Example 2.5.
C = A;
C(:,i) = B;
x(i,1) = det(C)/a_det;
end
Res = x’;
Python Solution
The following programming is the Python code, followed by the execution result that
determines the solution of the two linear algebraic equations defined in Example 2.5.
# Example 2.5
# Implementation f Cramer’s rule (2x2)
a = 12
b = 3
c = 2
d = -3
# Right-hand side
e = 15
f = 13
#12x+3y=15
#2x-3y=13
3x − 2 y = 4
6x − 4 y = 0
3 −2 x 4
A= , X = y , B = 0
6 −4
The determinant D
3 −2
D= = −12 + 12 = 0
6 −4
Simulink Solution
The Simulink reveals that there is no available solution for the matrix defined in
Example 2.6 because the determinant is zero (Figure 2.8).
The following program is the MATLAB code implanted in the Simulink MATLAB
function.
Python Solution
The following program is the Python code to find the determinant required in
Example 2.6.
# Example 2.6
#importing Numpy package
import numpy as np
# creating a 3X3 Numpy matrix
Numerical Solutions of Linear Systems 51
FIGURE 2.8 Simulink solution using Cramer’s rule encoded in MATLAB and implanted
in a Simulink MATLAB function representing the solution to the linear equations defined in
Example 2.6.
n_array = np.array([[3,-2],
[6,-4]])
Ax = b
52 Numerical Methods in Chemical Engineering Using Python® and Simulink®
The first equation is divided by a11 (a11 ≠ 0), multiplied by a21, and subtracted from
the second equation to yield the modified equation (2.2).
a
′ = a22 − 21 × a12
a22
a11
a
′ = a23 − 21 × a13
a23
a11
a
b2′ = b2 − 21 × b1
a11
Similarly, the first equation is divided by a11, multiplied by a31, and subtracted from
the third equation to yield the modified equation (2.3).
a
′ = a32 − 31 × a12
a32
a11
a
′ = a33 − 31 × a13
a33
a11
a
b3′ = b3 − 31 × b1
a11
Numerical Solutions of Linear Systems 53
The new row 2 equals row 2 – row 1 multiplied by (a21/a11 ), and the new row 3 equals
row 3 – row 1 (a31 / a11 ).
Finally, an upper triangular matrix is obtained. The three modified algebraic
equations are as follows:
′ x 2 + a2′ 3 x3 = b2′
a22
′′ x3 = b3′′3
a33
This is a new set of three linearly independent algebraic equations to solve. Reverse
substitution to determine x,
b′′3
x3 =
′′
a33
b2′ − a2′ 3 x3
x2 =
′
a22
b1 − a12 x 2 − a13 x3
x1 =
a11
∑
n
bii −1 − aiji−1x j
j = i +1
xi = i−1
a ii
Many equations of more than three require a program, such as Simulink or MATLAB
programming, to solve.
a11 a12
A=
a21 a22
Solution
a11 a12
A′ =
a21 ′
a22
a
′ = a22 − 21 × a12
a22
a11
The value of the determinant is not changed by the forward elimination step of the
Gauss elimination, and this must be true because the forward step only modifies
the equations.
Solve the following set of linear algebraic equations utilizing the Gauss elimination
method manually.
2x + y + z = 2
2 x + 2 y + 3z = 5
2 x + 3 y + 4 z = 11
Validate the manual calculations using Simulink and Python programming of the
Gauss elimination method.
Solution
′ , a23
Solving for a22 ′ , a32
′ , a33
′ , a2′ , b3′,
a 2
′ = a22 − 21 × a12 = 2 − × 1 = 1
a22
a11 2
a 2
′ = a23 − 21 × a13 = 3 − × 1 = 2
a23
a11 2
a 2
b2′ = b2 − 21 × b1 = 5 − × 2 = 3
a11 2
a 2
′ = a32 − 31 × a12 = 3 − × 1 = 2
a32
a11 2
a 2
′ = a33 − 31 × a13 = 4 − × 1 = 3
a33
a11 2
a 2
b3′ = b3 − 31 × b1 = 11− × 2 = 9
a11 2
The second step is to follow a similar procedure. In this case, the second row
'
becomes the pivotal equation and a22 abecomes pivotal elements.
where
a′ 2
a33 ′ − 32
′′ = a33 ' × a23
′ = 3 − × 2 = −1
a22 1
a′ 2
b3′′ = b3′ − 32 × b′22 = 9 − × 3 = 3
′
a22 1
56 Numerical Methods in Chemical Engineering Using Python® and Simulink®
2 1 1 x1 2
0 x
1 2 2 = 3
0 0 −1 x3 3
b3′′ 3
x3 = = = −3
′′
a33 −1
From the second last row,
Figure 2.9 shows the solution of the set of linear algebraic equations using the
‘Algebraic constraints’ block available in the Simulink Math functions library.
Note that when using the Gain to enter the matrix coefficient [2 1 1;2 2 3;2 3 4],
do not forget to select the ‘Matrix (K*u) (u vector)’ from the pulldown menu near
FIGURE 2.9 Simulation calculation using the Simulink algebraic constraint block for the
matrix given in Example 2.8.
Numerical Solutions of Linear Systems 57
FIGURE 2.10 Simulink solution using the Gauss elimination method coded in MATLAB
and implanted in the Simulink MATLAB function of equations specified in Example 2.8.
multiplication. An alternative way is to use the MATLAB function, where the Gauss
elimination method is programmed in the MATLAB file implanted in the MATLAB
function, followed by Figure 2.10. The Simulink results are the same as those
obtained using the Gauss elimination method.
The following program is the embedded MATLAB code utilizing the Gauss
elimination methods of the equations defined in Example 2.8.
function y = fcn(a)
% Code from “Gauss elimination and Gauss Jordan methods using
MATLAB.”
%Gauss elimination method [m,n)=size(a);[m,n]=size(a);
for j=1:m-1
for z=2:m
if a(j,j)==0
t=a(j,:);a(j,:)=a(z,:);a(z,:)=t;
end
end
for i=j+1:m
a(i,:)=a(i,:)-a(j,:)*(a(i,j)/a(j,j));
end
end
x=zeros(1,m);
for s=m:-1:1
c=0;
for k=2:m
c=c+a(s,k)*x(k);
end
x(s)=(a(s,n)-c)/a(s,s);
end
%display the results of the gauss elimination method;
y = x’;
58 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Python Solution
The following Python program solves systems of linear equations with n unknowns
using the Gauss elimination method. Given that a system is first transformed to
upper triangular matrix row operations, then the solution is obtained by a back-
ward substitution. The Python results are the same as those obtained manually
using the Gauss elimination method to solve the equation defined in Example 2.8.
Result
x = [-2.9.-3.]
Solve the following set of linear algebraic equations manually using the Gauss-
Jordan elimination methods.
x+ y−z = 7
x − y + 2z = 3
2x + y + z = 9
Verify the manual calculation using the Simulink and Python programming of the
Gauss-Jordan elimination method.
Solution
1 1 −1 7
1 −1 2 | 3
2 1 1 9
R1 − R2
1−1 = 0
1 − ( −1) = 2
−1 − ( 2 ) = −3
7−3= 4
1 1 −1 7
0 2 −3 | 4
2 1 1 9
1 1 −1 7
0 2 −3 | 4
0 −1 3 −5
60 Numerical Methods in Chemical Engineering Using Python® and Simulink®
R2 + 2 R3
0 + 2( 0 ) = 0
2 + 2 ( −1) = 0
−3 + 2 ( 3) = 3
4 + 2 ( −5) = −6
1 1 −1 7
0 2 −3 | 4
0 0 3 −6
3 1 0 17
0 2 −3 | 4
0 0 3 −6
3 1 0 17
0 2 0 | −2
0 0 3 −6
6 0 0 36
0 2 0 | −2
0 0 3 −6
Multiply the first row by 1 / 6, the second row by 1 / 2, and the third row by 1 / 3:
1 0 0 6
0 1 0 | −1
0 0 1 −2
Accordingly,
x = 6, y = −1, z = −2
Numerical Solutions of Linear Systems 61
Simulink Solution
The Simulink MATLAB function will return a column vector representing the solu-
tion to each variable in the order of appearance in the given matrix (Figure 2.11).
The following program is a MATLAB code associated with MATLAB function
programs Gauss-Jordan method to solve the matrix indicated in Example 2.9.
y = x(:,length(x))’;
Ans = y;
Python Solution
FIGURE 2.11 Simulink’s solution uses a Gauss-Jordan elimination method encoded in the
MATLAB and implanted in the Simulink MATLAB function to solve the matrix indicated
in Example 2.9.
62 Numerical Methods in Chemical Engineering Using Python® and Simulink®
column in the ending matrix representing the solution to the unknown variables.
Input: The function takes one matrix of n by n + 1, where n equals the number of
unknown variables. Each row represents the coefficients of the variables in each
equation. Furthermore, the last column contains the constants on the right-hand
side of each equation.
The above matrix is the augmented matrix of equations defined in Example 2.9,
whereas the second matrix is the same in the reduced row-echelon form in which
elements of the fourth column are the values of x, y, and z.
Gauss-Seidel methods is that in the Jacobi method, the value of the variables is not
modified until the next iteration, while in the Gauss-Seidel method, the values of the
variables are modified once a new value is evaluated.
a21x1 + a22 x 2 + … a2 n x n = b2
an1x1 + an 2 x 2 + … ann x n = bn
1
x1 = ( b1 − a12 x2 − a13 x3 − …a1n xn )
a11
1
x2 = ( b2 − a21x1 − a23 x3 − …a2n xn )
a22
1
xn =
ann
( bn − an1x1 − an 2 x2 − …an,n−1xn−1 )
Make an initial guess of x1o , x 2o , x no . Substitute these values into the right-hand side
of the rewritten equation to obtain the first approximation, x11 , x12 , x1n . Substitute the
computed approximation, x value, into the right-hand side of the rewritten equations.
This accomplished repeated iteration until forming a sequence of approximations.
Solve the following set of linear algebraic equations using the Jacobi method.
5x − 2 y + 3z = −1
−3 x + 9 y + z = 2
2 x − y − 7z = 3
TABLE 2.1
Approximate Solution Using the Jacobi Method of a Set of Equations Defined
in Example 2.10
n 0 1 2 3 4 5 6 7
x 0.000 –0.200 0.146 0.192 0.181 0.185 0.186 0.186
y 0.000 0.222 0.203 0.328 0.332 0.329 0.331 0.331
z 0.000 –0.429 –0.517 –0.416 –0.421 –0.424 –0.423 –0.423
Solution
1 2 3
x = − + y− z
5 5 5
2 3 1
y= + x− z
9 9 9
3 2 1
z=− + x− y
7 7 7
x11 = −0.200
y1 = 0.222
z1 = −0.429
Simulink Solution
%Example 2.10
function Res = jacobi(A,b)
Eps=0.001;
%[5 -2 3 ;-3 9 1; 2 -1 -7] equation coefficients
%[-1;2;3] equations right-hand side constants.
Numerical Solutions of Linear Systems 65
FIGURE 2.12 Simulink simulated block diagram using the Jacobi method coded in
MATLAB and inserted in the Simulink MATLAB function to solve the set of algebraic
equations given in Example 2.10.
n = length(b) ;
x0 = zeros(3,1) ;
x = ones(size(x0)) ;
while norm(x-x0,inf) >= Eps
x0 = x;
for i = 1 : n
x(i) = b(i);
for j = 1 : n
if j ~= i
x(i) = x(i) - A(i, j)*x0(j);
end
end
x(i) = x(i) / A(i, i) ;
end
end
Res =x’;
Python Solution
The Jacobi method is an iterative matrix used to solve the equation A X = b for
a known square matrix of size n × n and known vector or length. The follow-
ing Python code utilizes the Jacobi method to solve the equations defined in
Example 2.10.
# Example 2.10
# Jacobi method
f1 = lambda x, y, z : (-1 +2*y - 3*z)/5
f2 = lambda x, y, z : (2 + 3*x - z)/9
f3 = lambda x, y, z : (-3 + 2*x-y)/7
# Tolerance
e = 0.0001
iteration = 0
66 Numerical Methods in Chemical Engineering Using Python® and Simulink®
# initial values
x0 = y0 = z0 = 0
e1 = e2 = e3 = 1
print(“\n n x y z \n”)
while e1>e and e2>e and e3>e:
x1 = f1(x0,y0,z0)
y1 = f2(x0,y0,z0)
z1 = f3(x0,y0,z0)
e1 = abs (x0-x1)
e2 = abs (y0-y1)
e3 = abs (z0-z1)
iteration +=1
x0 = x1
y0 = y1
z0 = z1
print(f”{{y1:.3f} {z1:.3f}”)
print (f”\n The value of x = {x1:.3f},y= {y1:.3f},z= {z1:.3f}”)
print(f”\n number of iteratios = {iteration}”)
Execution result
n x y z
1.0 -0.200 0.222 -0.429
2.0 0.146 0.203 -0.517
3.0 0.192 0.328 -0.416
4.0 0.181 0.332 -0.421
5.0 0.185 0.329 -0.424
6.0 0.186 0.331 -0.423
7.0 0.186 0.331 -0.423
1. Guess every unknown value in the matrix. Assume a value for as many vari-
ables as x, y, and z. Set the initial iteration to 0, as many programming lan-
guages like Python have zero indexing, meaning we begin counting from 0.
However, if using MATLAB, begin at 1, as it does not have zero indexing. A
typical starting guess is just a zero matrix unless we have additional infor-
mation about the problem that could help our guesses. The benefit of having
a better starting guess is that we achieve our final solution in fewer iterations
and, therefore, less time.
2. Rewrite all of our independent equations and have them all solve for an
individual variable.
3. Once we have rewritten all of our system of linear equations, it is often wise
at this point to create a table to summarize all of the relevant information.
Numerical Solutions of Linear Systems 67
Now we are ready to solve for iteration 1 user’s latest guesses of y and z year
to help us solve for x at iteration 1. Then we must solve for y and use our
latest guesses for x and z. Note that this is where the significant difference
between the Jacobi iteration method and the Gauss-Seidel method is in the
Jacobi method; we would not use the variable values in the same iteration
on one another. However, in the Gauss-Seidel method, we do, which almost
always leads to finding a solution quicker if there is one. Last, move on to
solving z for iteration using x and y that we found in the first iteration.
4. After finding all the variable values for iteration 1, move forward to iteration
2 and solve for x using the y and z values found in iteration 1.
5. Continue iterations until there is an acceptable amount of error. For coding
purposes, verify that all equations’ right sides are within the error tolerance.
The Gauss-Seidel method is used to solve linear system equations. This method
modifies the Gauss-iteration method and the Jacobi method. This modification
reduces the number of iterations. The computed value replaces the previous value
only at the end of the iteration. Because of this, Gauss-Seidel methods converge
much faster than Gauss methods. The number of iteration methods required to get
the solution is much less than the Gauss method in Gauss-Seidel methods. The
Gauss-Seidel equation
n
xi =
1
aii
(bi − ∑
j =1, j ≠ i
aij x j )
Use the approximate solution utilizing the Gauss-Seidel iteration method to solve
the following set of three linear algebraic equations.
5x − 2 y + 3z = −1
−3 x + 9 y + z = 2
2 x − y − 7z = 3
x=
( −1 + 2y − 3z )
5
y=
( 2 + 3x − z )
9
z=
( −3 + 2x − y )
7
68 Numerical Methods in Chemical Engineering Using Python® and Simulink®
TABLE 2.2
Approximate Solution Using the Gauss-Seidel
Method of the Set of Equations Defined in
Example 2.11
n 0 1 2 3 4 5
𝑥 0.000 –0.200 0.167 0.191 0.186 0.186
𝑦 0.000 0.156 0.334 0.333 0.331 0.331
𝑧 0.000 –0.508 –0.429 –0.422 –0.423 –0.423
The first calculation is the same as the Jacobi iteration method, as a first initial
guess.
x= y=z=0
1 2 3
x1 = − + ( 0 ) − ( 0 ) = −0.200
5 5 5
The value of y, is obtained by substituting the new value of x1 = −0.200, in the
commutation of y
2 3 1
y= + ( −0.200 ) − ( 0 ) = 0.156
9 9 9
In the computation of z, substitute the new values of x, y
3 3 1
z=− + ( −0.200 ) − ( 0.156 ) = −0.508
7 9 7
Continue the iterations until successive values are identical to the three decimal
digits. The sequence of approximations is shown in Table 2.2. The solution con-
verges in less number of iterations.
Simulink Solution
The Simulink block diagram using the Simulink MATLAB function is presented in
Figure 2.13, followed by the MATLAB code.
The following MATLAB program is the MATLAB code embedded in the
Simulink MATLAB function utilizing the Gauss-Seidel iteration method of the set
of equations presented in Figure 2.13.
% Example 2.11.
% Gauss-Seidel iteration method
function Res = gauss(A,b)
%This function solves the system of algebraic equations using the
%Gaussian method
Numerical Solutions of Linear Systems 69
%Ax=b
%Input: matrix A,column vector b
%Output vector x
n=size(A,1);
b=b(:);%make sure b is a column vector.
nb=n+1;
Ab=[A b];%extended matrix
%Forward process
for i=1:n-1
for j=i+1:n
Ab(j,i:nb)=Ab(j,i:nb)-Ab(j,i)*Ab(i,i:nb)/Ab(i,i);
end
end
%Inverse process
x=zeros(n,1);
x(n)=Ab(n,nb)/Ab(n,n);
for i=n-1:-1:1
x(i)=(Ab(i,nb)-Ab(i,i+1:n)*x(i+1:n))/Ab(i,i);
end
Res = x;
Python Solution
The following program is the Python code utilizing the Gauss-Seidel method to
solve the equations defined in Example 2.11.
# Example 2.11
# Guass Seidel method
f1 = lambda x,y,z:(-1 + 2*y - 3*z)/5
f2 = lambda x,y,z:(2 + 3*x - z)/9
f3 = lambda x,y,z:(-3 + 2*x-y)/7
70 Numerical Methods in Chemical Engineering Using Python® and Simulink®
# Tolerance
e = 0.0001
iteration = 0
# initial values
x0 = y0 = z0 = 0
e1 = e2 = e3 = 1
print(“\n n x y z \n”)
while e1>e and e2>e and e3>e:
x1 = f1(x0,y0,z0)
y1 = f2(x1,y0,z0)
z1 = f3(x1,y1,z0)
e1 = abs (x0-x1)
e2 = abs (y0-y1)
e3 = abs (z0-z1)
iteration +=1
x0 = x1
y0 = y1
z0 = z1
print(f”{iteration:.1f} {x1:.3f} {y1:.3f} {z1:.3f}”)
print (f”\n The value of x = {x1:.3f},y = {y1:.3f},z = {z1:.3f}”)
print(f”\n number of iteratios = {iteration}”)
Execution result
n x y z
1.0 -0.200 0.156 -0.508
2.0 0.167 0.334 -0.429
3.0 0.191 0.333 -0.422
4.0 0.186 0.331 -0.423
5.0 0.186 0.331 -0.423
2.6 SUMMARY
Solving linear systems is fundamental to numerical computation. Binary and tertiary
linear systems are easily solved by successive substitution, and the general linear
system can be solved by triangulation and Gaussian elimination. Pivoting is essential
for the stable implementation of Gaussian elimination. Algorithms and specialized
software are available to solve specific types of linear systems using Simulink and
Python.
2.7 PROBLEMS
1. Find the determinant of the following 2 × 2 matrix:
−4 2
−8 7
Numerical Solutions of Linear Systems 71
6 2 −4
5 6 −2
5 2 −3
5x + y = −13
3x − 2 y = 0
−2 x + 3 y = −3
3x − 4 y = 5
−8 x − 6 y = −2
2 x + 5 y = −1
−2 x + y − z = 8
−3 x − y + 2 z = −11
−2 x + y + 2z = −3
7. Solve the system shown below using the Gauss elimination method.
x + y− z = 9
y + 3z = 3
72 Numerical Methods in Chemical Engineering Using Python® and Simulink®
−x − 2 z = 2
−x + 2 y = −6
3 x − 4 y = 14
2 x + y + 2 z = 10
x + 2y + z = 8
3x + y − z = 2
x+ y+z = 4
2x − 3y + z = 2
−x + 2 y − z = −1
REFERENCE
3 Bracketing Numerical
Methods for Solving
Systems of Nonlinear
Equations
Root-finding methods of nonlinear algebraic equations are categorized into brack-
eted and open methods. This chapter covers the graphical and bracketing methods
such as the bisection method, the false-position method, and the Ridders method.
Programming these methods using Simulink and the open-source Python language
is explained extensively.
LEARNING OBJECTIVES
1. Determine the approximate roots of nonlinear equations using the graphical
method.
2. Calculate the roots of nonlinear equations using the bisection method.
3. Estimate the approximate roots of nonlinear equations using the false-posi-
tion method.
4. Find the roots of nonlinear equations using the Ridders method.
3.1 INTRODUCTION
Most numerical methods for finding roots of linear and nonlinear algebraic equations
use repetition, resulting in a series of numbers that expectantly approach the root as
a bound. It requires one or more initial guesses of the root as initial values, and then
each iteration of the algorithm results in a more accurate approximation of the root
successively.
Nonlinear equations involve multiple variables. To recognize a nonlinear equation
is to observe that the x is not alone as in ax, but involves a product with itself, such as
in x3 + 3x2 – 9 = 0. In this case, x3 and 2x2 are nonlinear terms. The differences between
‘closed’ and ‘open’ methods are that the closed method uses a bounded interval. This
method usually converges slowly and always finds a root if it exists. The open method
usually converges quickly; many do not find a root if it exists. The available methods
require a single or two starting values that do not necessarily bracket a root. Closed
methods generate at least one root. Depending on the initial guess and type of function,
the available methods sometimes result in divergence. By contrast, once converged,
they are faster than closed methods and converged quickly. The bracketing methods
DOI: 10.1201/9781003360544-3 73
74 Numerical Methods in Chemical Engineering Using Python and Simulink
include graphical, bisection, and false-position methods. The following equations are a
set of the nonlinear algebraic equations:
f1 ( x1 ……… x n ) = 0
f2 ( x1 ………x n ) = 0 = f ( x ) (3.1)
fn ( x1 ……...x n ) = 0
or
f (x )
( )
F X = ... =0 (3.2)
fn ( x )
( )
where F1 X takes the form such as ( X1 − sin X1 ) = 0, or
Solving a set of nonlinear algebraic equations usually is difficult. Solving one non-
linear equation f (α ) = 0, finding the root (α ).
f (x) = 0
f ( x ) = f1 ( x ) − f2 ( x )
Using the graphical method, find the roots of the following equation:
f ( x ) = x 3 − 3x 2 − 3x + 1 = 0
Validate the manual calculations with Simulink and Python programming of the
root finding using a graphical method.
Solution
f1 ( x ) = x 3
f2 ( x ) = 3 x 2 + 3 x − 1
So that
( ) ( )
f ( x ) = f1 ( x ) − f2 ( x ) = 3 x 3 − 3 x 2 + 3 x − 1
Simulink Solution
Figure 3.1 symbolizes the Simulink block diagram utilizing the graphical method to
solve the equation defined in Example 3.1.
To enter the X and Y label in the scope, select the X-Y graph generated by
Simulink, and then run the below commands in the MATLAB command window:
set(0,’ShowHiddenHandles’, ‘on’)
set(gcf, ‘menubar’, ‘figure’)
These commands will enable the toolbar in the X − Y graph figure window. Individuals
can add axes names from Insert >> X Label and Insert >> Y Label (Figure 3.2).
TABLE 3.1
Values of f(x) at Various x Values
x –4 –3 –2 –1 0 1 2 3 4
f1(x) –64 –27 –8 –1 0 1 8 27 64
f2(x) 35 17 5 –1 –1 5 17 35 59
76 Numerical Methods in Chemical Engineering Using Python and Simulink
FIGURE 3.1 Simulink programming utilizes a graphical method to solve the equation
defined in Example 3.1.
FIGURE 3.2 Graphical representation using the graphical root finding of the equation
defined in Example 3.1.
Bracketing Numerical Methods 77
Python Solution
The following program is the Python code that generates the plot shown in
Figure 3.3. The figure represents the graphical root-finding method of the equation
defined in Example 3.1.
# Example 3.1
# Bisection method
import numpy as np
import matplotlib.pyplot as plt
def f(x):
y= x**3 - 3*x**2 - 3*x + 1
return y
def g(x):
y1 = x**3
return y1
def h(x):
y2 = 3*x**2 + 3*x - 1
return y2
a = -5
b = 5
def bisection(a, b):
if f(a)*f(b)>0:
print(“no root found”)
return
c = a
while ((b-a)>=0.01):
c = (a +b)/2
if f(c)==0:
exit()
if f(c)*f(a)<0:
b = c
else:
a = c
FIGURE 3.3 Find the root plot generated by Python programming for the graphical method
of the given equation in Example 3.1.
78 Numerical Methods in Chemical Engineering Using Python and Simulink
print(“root of of i=”, c)
plt.plot(c, f(c), ‘ro’)
bisection(a, b)
x=np.linspace(-3,3,20)
plt.plot (x, g(x), x, h(x), x, f(x))
plt.grid()
plt.xlabel(“x”, fontsize = 15)
plt.ylabel(“y”, fontsize = 15, rotation = 0)
plt.text(-2,20, ‘Roots are at the intersections of
\n $y_1$ and $y_2$’)
plt.text(-2.5,-40, ‘$y=x^3 - 3x^2 - 3x + 1$’)
plt.text(2,30, ‘$y_1= x^3$’)
plt.text(1.2,-2, ‘$y_2= 3x^2 + 3x - 1$’)
Find the root of the following equation using the graphical method.
f ( x ) = x 4 − 11x 2 + 2 x + 1
Validate the manual calculation of the root using Simulink and Python program-
ming of the graphical method.
Solution
f1 ( x ) = x 4
f2 ( x ) = 11x 2 − 2 x − 1
( ) (
f ( x ) = f1 ( x ) − f2 ( x ) = x 4 − 11x 2 − 2 x − 1)
The root is at x where
f1 ( x ) = f2 ( x )
Taking an appropriate value of x to generate the data shown in Table 3.2. Two
roots exist at x = −0.22437, and x = 0.40987. At these values, differences between
f1 ( x ) and f2 ( x ) equal zero.
TABLE 3.2
Values of f(x) at Various Values of x
x –4 –3 –2 –1 –0.22437 0 0.40987 1 2 3 4
f1(x) 256 81 16 1 0.0025 0 0.0282 1 16 81 256
f2(x) 183 104 47 12 0.0025 –1 0.0282 8 39 92 167
Bracketing Numerical Methods 79
Simulink Solution
FIGURE 3.4 The Simulink block diagram represents the method for finding the root by the
graphical approach of the given equation in Example 3.2.
FIGURE 3.5 Simulink generated a plot of the graphical root-finding representation of the
equation identified in Example 3.2.
80 Numerical Methods in Chemical Engineering Using Python and Simulink
Python Solution
The following Python code uses the graphical root-finding method to solve the
equation defined in Example 3.2. Figure 3.6 shows the plot with the intersections
where the root lies.
# Example 3.2
# Graphical and Bisection method
import numpy as np
import matplotlib.pyplot as plt
def f(x):
y= x**4–11*x**2+2*x+1
return y
def g(x):
y1 = x**4
return y1
def h(x):
y2 = 11*x**2-2*x-1
return y2
a = 0
b = 2
def bisection(a, b):
if f(a)*f(b)>0:
print(“no root found”)
return
c = a
while ((b-a)>=0.0001):
c = (a +b)/2
if f(c)==0:
exit()
if f(c)*f(a)<0:
b = c
else:
a = c
FIGURE 3.6 Python-generated plot of the root finding using the graphical technique of the
equation defined in Example 3.2.
Bracketing Numerical Methods 81
print(“root of of i=”, c)
plt.plot(c, f(c), ‘ro’)
bisection(a, b)
x=np.linspace(-1,1,20)
plt.plot (x, g(x), ‘g’, x, h(x), ‘b’, x, f(x), ‘r’)
plt.grid()
plt.xlabel(“x”, fontsize = 12)
plt.ylabel(“y”, fontsize = 12, rotation=0)
plt.text(-0.5,7, ‘Roots are at the intersections of
\n $y_1$ and $y_2$’)
plt.text(-0.75,-10, ‘$y=x^4–11x^2+2x+1$’)
plt.text(-1,5, ‘$y_1= x^4$’)
plt.text(-1,-2, ‘$y_2= 11x^2-2x-1$’)
Find the roots of the following quadratic equation using manual calculations,
Python programming, and Simuling graphical programming.
y = x2 − 4x + 3 = 0
Confirm the manual calculation using the graphical root-finding method utilizing
Simulink and Python programming.
Manual Solution
x2 − 4x + 3 = 0
( x − 3)( x − 1) = 0
Simulink Solution
Figure 3.7 shows the Simulink block diagram representing the graphical root-
finding method of the equation defined in Example 3.3. The intersection points
represent the roots of the quadratic equations (Figure 3.8).
Python Solution
The following Python code describes the graphical root-finding method of the
equation defined in Example 3.3. After execution, the results are plotted in
Figure 3.9.
# Example 3.3
# Graphical & Bisection methods
import numpy as np
import matplotlib.pyplot as plt
def f(x):
82 Numerical Methods in Chemical Engineering Using Python and Simulink
FIGURE 3.7 Simulink block diagram utilizing the graphical method to solve the equation
declared in Example 3.3.
FIGURE 3.8 Simulink generated a plot of a graphical representation of the quadratic equa-
tion mentioned in Example 3.3.
Bracketing Numerical Methods 83
FIGURE 3.9 Root finding using the graphical method in Python of the equation described
in Example 3.3.
y = x**2 - 4*x + 3
return y
def g(x):
y1 = x**2
return y1
def h(x):
y2=4*x - 3
return y2
a = 2
b = 5
def bisection(a, b):
if f(a)*f(b)>0:
print(“no root found”)
return
c = a
while ((b-a)>=0.01):
c = (a +b)/2
if f(c)==0:
exit()
if f(c)*f(a)<0:
b = c
else:
a = c
print(“root of of i=”, c)
plt.plot(c, f(c), ‘ro’)
bisection(a, b)
x=np.linspace(0,5,10)
plt.plot (x, g(x), x, h(x), x, f(x))
plt.grid()
plt.xlabel(“x”, fontsize = 12)
plt.ylabel(“y”, fontsize = 12, rotation=0)
plt.text(0.2,20, ‘Roots are at the intersections’)
plt.text(3.5,-0.5, ‘$y=x^2–4x+3$’)
plt.text(3.8,20, ‘$y= x^2$’)
plt.text(4,12, ‘$y=4x-3$’)
84 Numerical Methods in Chemical Engineering Using Python and Simulink
Find the roots of the following equation using the graphical method.
y = ex + x − 3
ex = 3 − x
There is one root which is around 0.8. Validate the root found manually with the
graphical method using Simulink and Python programming.
Simulink Solution
Figure 3.10 is a Simulink block diagram describing a graphical method for find-
ing the root of the equation given in Example 3.4, and the output is displayed in
Figure 3.11.
Python Solution
The following Python code uses the graphical root search method programmed to
find one of the roots of the equation given in Example 3.4.
# Example 3.4
import numpy as np
import matplotlib.pyplot as plt
def f(x):
y = np.exp(x) + x - 3
FIGURE 3.10 Simulink graphical root-finding method of the equation defined in Example
3.4.
Bracketing Numerical Methods 85
return y
def g(x):
y1 = np.exp(x)
return y1
def h(x):
y2= 3-x
return y2
# interval [a, b]
a = 0
b = 3
def bisection(a, b):
if f(a)*f(b)>0:
print(“no root found”)
return
c = a
while ((b-a)>=0.01):
c = (a + b)/2
if f(c)==0:
exit()
if f(c)*f(a)<0:
b = c
else:
a = c
print(“The root of the function :”, c)
FIGURE 3.11 Simulink generated a plot of the graphical root-finding method to solve the
equation defined in Example 3.4.
86 Numerical Methods in Chemical Engineering Using Python and Simulink
FIGURE 3.12 Graphical method for finding the root of the equation defined in Example 3.4
using Python.
Find the roots of the following equation using the graphical root-finding method.
y = ln ( x ) + x − 3
Using Simulink and Python programming to find the root of the defined equation.
Solution
Simulink Solution
The Simulink solution utilizing the graphical root-finding method of the equation
present in Example 3.5 is shown in Figures 3.13 and 3.14.
FIGURE 3.13 Simulink graphical simulation method of finding the root with a cut-off time
is five to solve the given equation in Example 3.5.
Python solution
# Example 3.5
import numpy as np
import matplotlib.pyplot as plt
def f(x):
y = np.log(x) + x - 3
return y
def g(x):
y1 = np.log(x)
return y1
def h(x):
y2= 3-x
return y2
# interval [a, b]
a = 0
b = 5
def bisection(a, b):
if f(a)*f(b)>0:
print(“no root found”)
return
c = a
while ((b-a)>=0.01):
c = (a +b)/2
if f(c)==0:
exit()
if f(c)*f(a)<0:
b = c
else:
a = c
print(“The root is:”, c)
plt.plot(c, g(c), ‘ro’)
bisection(a, b)
x=np.linspace(0,5,30)
plt.plot (x, g(x), x, h(x), x, f(x))
plt.grid()
plt.xlabel(“x”, fontsize = 13)
plt.ylabel(“y”, fontsize = 13, rotation=0)
plt.text(0.65,2.5,’Roots are at the intersections of’
‘\n $y_1=3-x$ & $y_2=ln(x)$’, fontsize = 12)
plt.text(1.3,-2, ‘$y=ln(x)+x-3$’, fontsize = 13)
plt.text(4,0.5, ‘$y_2=ln(x)$’, fontsize = 12)
plt.text(0.1,1.5, ‘$y_1=3-x$’, fontsize = 12)
FIGURE 3.15 Python-generated plot represents the graphical root-finding method of the
equation present in Example 3.5.
f ( xl ) × f ( xu ) < 0
This means that one root was trapped or enclosed in parentheses. Some
functions may have multiple roots.
3.3.1 Bisection Method
The bisection method is a type of root-finding bracketing method in which the inter-
val is always divided in half. If the function changes signs over an interval, the value
of the function will be evaluated at the midpoint. The root location is then identified
as within the subinterval where the tag change occurs. The bisection method requires
two initial guesses:
a = x 0 and b = x1, to satisfy the bracket condition
f ( x 0 ) · f ( x1 ) < 0
To check for a root of some function, f ( x ), select an interval [ x o , x1 ] in which the root
lies in between x o and x1.
1. Calculate f ( x 0 ) and f ( x1 ).
2. Check to see if they have the same sign. If so, there may be no root between
them, and then quit.
3. If they have opposite signs, then pick a point, f ( xi ) between the two ends.
4. Check the sign of the f ( xi ), if it is signed the same as f ( x1 ), the root lies
between xi and x 2, so set x1 = xi.
5. If it is signed the same as f ( x1 ), then the root lies between xi and x1, so set
xi as x1.
6. If f ( xi ) = 0, then xi is the root.
7. Otherwise, repeat with new xi .
Use the bisectional method to find the root of the following equation on the inter-
val [1, 2].
f (x) = x2 − 3
Bracketing Numerical Methods 91
Stop when the relative fraction change is 1 × 10 −5. The exact root is ∓ 3 . Verify the
exact root with Simulink and Python programming of the bisection method.
Solution
f ( x 0 = 1) = 12 − 3 = 1 – 3 = −2 < 0
f ( x1 = 2 ) = 22 − 3 = 4 – 3 = 1 > 0
The given function is continuous, and the root lies in the interval [1, 2]. The value
of the lower limit is negative, and the upper interval is positive. Let ‘xi’ be the
midpoint of the interval. We calculate the f ( x1 = 1 ) and f ( x 2 = 2) the first guess is
the midpoint of the interval, xi = 1.5, and then we evaluate the function f ( xi = 1.5).
(1 + 2)
xi = = 1.5
2
Therefore, the value of the function at xi is
% Example 3.6
% Bisection Method in MATLAB
function y = fcn(a, b)
TABLE 3.3
Solution of Equation Present in Example 3.6 Using the Bisectional Method
Iterations a b xi f(a) f(b) f(xi)
1 1 2 1.5 –2 1 -0.75
2 1.5 2 1.75 –0.75 1 0.062
3 1.5 1.75 1.625 –0.75 0.0625 –0.359
4 1.625 1.75 1.6875 –0.3594 0.0625 –0.1523
5 1.6875 1.75 1.7188 –1523 0.0625 –0.0457
6 1.7188 1.75 1.7344 –0.0457 0.0625 0.0081
7 1.7188 1.7344 1.7266 –0.0457 0.0081 –0.0189
92 Numerical Methods in Chemical Engineering Using Python and Simulink
FIGURE 3.17 Simulink solution using the ‘algebraic constraint’ of the equation defined in
Example 3.6.
FIGURE 3.18 Simulink solution using the MATLAB function and the associated
MATLAB coding of the bisection method programmed in MATLAB of the equation
defined in Example 3.6.
f = @(x)(x^2–3);
%a = 1;
%b = 2;
eps = 0.001;
m = (a+b)/2;
fprintf(‘\n The value of, after bisection method, m
is %f\n’, m);
while abs(b-a)>eps
if (f(a)*f(m))<0
b=m;
else
a=m;
end
m = (a+b)/2;
end
y = m;
Bracketing Numerical Methods 93
Python solution
The following program is the Python code for finding one of the roots of the equa-
tion exhibited in Example 3.6.
#Example 3.6
# Our f(x) function
def f(x):
y = x**2–3
return y
# Function to update R
def UpdateBisec(L, U):
R = (L + U)/2
return R
# The Bisection method (BSM) function
def BSM(f, L, U):
R = UpdateBisec(L, U)
while abs(f(R)) > 1e-3:
if f(L) * f(R) < 0:
U = R
elif f(U) * f(R) < 0:
L = R
elif f(R) == 0:
return R
R = UpdateBisec(L, U)
return R
Root= BSM(f, 0, 5)
print (“The calculated root is =”, root)
The results:
Solve the following equation using the regula-falsi method up to three decimal
places within the interval [0,1].
f ( x ) = x3 − 4x + 1
Verify the manual calculations with Simulink and Python programming of the
regula-falsi method.
94 Numerical Methods in Chemical Engineering Using Python and Simulink
Solution
f ( 0 ) = 03 − 4 ( 0 ) + 1 = 1
Because the value of f ( 0 ) is positive and the value of f (1) is negative, accordingly,
the root lies between 0 and 1.
af ( b ) − bf ( a ) 0 ( −2 ) − 1(1)
x1 = = = 0.333
f (b) − f (a) −2 − 1
Since the value is negative, the root lies between a and x1, and it will replace b
af ( x1 ) − x1 f ( a )
x2 =
( f ( x1 ) − f ( a ))
Substitute the values
Since the value of f ( x 2 ) is negative; the root lies between a and x 2 , accordingly,
af ( x 2 ) − x 2 f ( a )
x3 =
( f ( x2 ) − f ( a ))
Bracketing Numerical Methods 95
Substitution
0 ( −0.0115) − 0.2571(1)
x3 = = 0.2541
( −0.0115 − 1)
Find f ( x3 )
x3 f ( x 2 ) − x 2 f ( x3 )
x4 =
f ( x 2 ) − f ( x3 )
Figure 3.20 represents the Simulink block diagram using the algebraic constraints
for finding the root of the equation required in Example 3.7.
An alternative way is to program the regula-falsi method using the MATLAB
function built in the Simulink library. The Simulink block diagram shown in
Figure 3.21 describes the solution of Example 3.7.
The following program is the MATLAB code associated with the MATLAB func-
tion using the regula-falsi method to solve the equation described in Example 3.7.
FIGURE 3.20 Simulink block diagram using the ‘algebraic constraints’ represents the solu-
tion of the equation required to find its root in Example 3.7.
96 Numerical Methods in Chemical Engineering Using Python and Simulink
FIGURE 3.21 Regula-falsi method for solving the equation required in Example 3.7.
%Example 3.7
%Using False Position Method
% Find out the root of a function
function y = fcn(a, b)
% within the interval [a, b]
x0=a;
x1=b;
tol=0.001;
n=100;
f=@(x)x^3–4*x + 1;
y0=f(x0);
y1=f(x1);
i=1;
while i<=n
x=x1-y1*(x1-x0)/(y1-y0);
if abs(x-x1)<tol
disp(‘Root of function:’);
disp(x);
break
end
i=i+1;
y=x^3–4*x + 1;
if y0*y1<0
x0=x;
y0=y;
else
x1=x;
y1=y;
end
end
y = x1;
Bracketing Numerical Methods 97
Python solution
The following program is the Python code that uses the false-position method,
representing the equation’s solution defined in Example 3.5.
# Example 3.7
# False Position method (FPM)
# import numpy as np
# Our f(x) function
def f(x):
y = x**3 - 4*x +1
return y
# Function to update R
def UpdateFalseP(f, L, U):
R = U - (f(U) * (L - U))/(f(L) - f(U))
return R
# The False Position method function
def FPM(f, L, U):
R = UpdateFalseP(f, L, U)
while abs(f(R)) > 1e-3:
if f(L) * f(R) < 0:
U = R
elif f(U) * f(R) < 0:
L = R
elif f(R) == 0:
return R
R = UpdateFalseP(f, L, U)
return R
Root = FPM(f, 0, 1)
print (“\n The calculated root = “, Root)
Output
f ( x o ) × f ( x1 ) < 0
x 0 + x1
u=
2
98 Numerical Methods in Chemical Engineering Using Python and Simulink
x 0 + x1 x1 − x 0 sin f ( x o ) − f ( x1 ) f ( u )
x2 = + .
2 2 f 2 ( u ) − f ( x o ) f ( x1 )
Solve the following equation using the Ridders method within the interval [0.0,0.5].
f ( x ) = x3 − 4x + 1
Verify the manual calculations with Simulink and Python programming of the
Ridders method.
Solution
f ( x o ) × f ( x1 ) < 0
f ( xo ) = f ( 0 ) = 1
f ( x1 ) = f ( 0.5) = −0.875
Bracketing Numerical Methods 99
x 0 + x1 0 + 0.5
u1 = = = 0.25
2 2
x 0 + x1 x1 − x 0 sin f ( x o ) − f ( x1 ) f ( u1 )
x2 = + .
2 2 f 2 ( u ) − f ( x o ) f ( x1 )
The new interval should depend on f ( x1 ) f ( x 2 ) < 0 an x 2 should be the end of the
interval,
f ( x0 ) = f ( 0 ) = 1
f ( x1 ) = f ( 0.5) = −0.875
f ( x 2 ) = f ( 0.25417 ) = −0.00028
Since the new value ( x 2 ) is close to zero, it is considered one of the roots of the
equation.
Simulink Solution
%Example 3.8
%Using Ridders Method
% Find out the root of a function
function root = riddler(a, b)
xl=a;
xh=b;
func=@(x)x^3–4*x + 1;
fl=func(a);
100 Numerical Methods in Chemical Engineering Using Python and Simulink
FIGURE 3.23 Simulink solution utilizing Ridder’s method to solve the equation defined in
Example 3.8.
fh=func(b);
tol=0.001;
N=100;
root = 0;
for i = 1:N
xm = 0.5*(xl+xh);
fm = func(xm);
s = sqrt(fm*fm - fl*fh);
if s == 0
return;
end
xnew = xm + (xm - xl)*sign(fl - fh)*fm/s ;
root =xnew;
if (xnew-xm) <tol
return
end
Python Solution
The following program deals with the Ridders numerical method using Python
language to solve the equation specified in Example 3.8.
# Example 3.8
‘‘‘ Finds a root of f(x) = 0 with Ridder’s method.
The root must be bracketed in (a, b).
‘‘‘
from numpy import sign
from numpy import sqrt
Bracketing Numerical Methods 101
xl=0.0
xh=0.5
def func(x):
return x**3–4*x + 1
fl=func(xl)
fh=func(xh)
tol=0.001
N=100
root = 0;
N=100
for i in range(0, N):
xm = 0.5*(xl+xh)
fm = func(xm)
s = sqrt(fm*fm - fl*fh)
if s == 0:
exit()
xnew = xm + (xm - xl)*sign(fl - fh)*fm/s
if (xnew-xm) <tol:
exit()
# print the root
print (‘The Root is‘, xnew)
3.4 SUMMARY
Graphical methods are a straightforward way to estimate the root of equation,
f ( x ) = 0. We can approximate the root if we plot the function f ( x ) = 0 and note
where it intersects the x-axis. The bracketing methods are based on the mean value
theory, and the bisection method is a bracketing type of the root-finding method. The
bisection method decreases the error by a constant factor by each iteration, referred
to as linear convergence. The Ridders method is a root-finding algorithm based on
the false-position method and uses an exponential function to approximate the root
of a continuous function successively.
3.5 PROBLEMS
y = x2 − 4x + 3
f (x) = x2 − 3
102 Numerical Methods in Chemical Engineering Using Python and Simulink
f ( x ) = x 2 + 2x – 8
f ( x ) = x3 − x − 1
Answer: (1.325)
f ( x ) = x3 − 5
x 3 − 6 x 2 + 11x − 6 = 0
f ( x ) = e x − sin ( x ) = 0
f ( x ) = x + ln ( x ) = 0
10. Find the roots of the following equation using the graphical method within
the interval [–1 1].
f ( x ) = x 2 − tan ( x ) = 0
REFERENCE
4 Open Numerical
Methods for Solving
Systems of Nonlinear
Equations
An equation is said to be nonlinear when it involves terms of a degree higher than 1
in an unknown quantity. Several methods can be used to numerically solve a nonlin-
ear system of equations, and Newton’s method is the most feasible method to solve
systems of nonlinear equations. This chapter studied open root-finding methods such
as the method of substitution, fixed-point iteration method, Newton-Raphson (NR)
method, secant method, and Muller’s method.
LEARNING OBJECTIVES
1. Use the method of substitution for solving simultaneous equations.
2. Utilize the fixed-point iteration method to solve equations of the form
f ( x ) = 0.
3. Employ the NR method for solving equations numerically.
4. Apply the secant method for root finding.
5. Apply Muller’s method to solve equations of the form f ( x ) = 0 .
4.1 INTRODUCTION
Nonlinear algebraic equations are one of the subjects in mathematics. A system of
nonlinear equations is a system of two or more equations in two or more variables
containing at least one equation that is not linear. Any equation that cannot be writ-
ten in the following form is considered nonlinear [1].
Ax + By + C = 0 (4.1)
x 2 − 6x + 9 = 0 (4.2)
x − sin ( x ) = 0 (4.3)
(1 − x ) y 2 − x 3 = 0 (4.4)
y2 + x 2 − 1 = 0 (4.5)
The open methods do not restrict the root from remaining trapped in a closed inter-
val. Accordingly, they are not as robust as bracketing methods and can divert, and
they are more difficult to obtain compared to closed methods. The most popular are
Newton’s method, the secant method, and Muller’s method.
Suppose we have the following algebraic equations and we want to use the substitu-
tion method to solve the two algebraic equations:
y − 2x = 8 (4.6)
y = 5− x (4.7)
y = 8 + 2x (4.8)
Open Numerical Methods 105
(8 + 2 x ) = 5 − x (4.9)
8 − 5 = −2 x − x = −3x (4.10)
3 = −3 x
(4.11)
x = −1
y − 2x = 8 (4.12)
y − 2 ( −1) = 8
(4.13)
y=6
y = x +1
y = x2 + 1
Solution
Solve for x
x = y −1
y = ( y − 1) + 1
2
Simplify
y = y2 − 2 y + 2
106 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Rearrange
0 = y2 − 3y + 2
Factorize
( y − 2)( y − 1) = 0
Solving for y, gives y = 1 and y = 2.
Substitute each value of y in the first equation to find the value of x.
For y = 1,
x − 1 = −1
x=0
For y = 2,
x − 2 = −1
x =1
Figure 4.1 represents the Simulink block diagram using the MATLAB function
dragged from the Simulink/User-Defined Functions library [2]. The MATLAB code
is associated with the MATLAB function. The MATLAB function is attached to two
FIGURE 4.1 Graphical demonstration of the solution of equation present in Example 4.1.
Open Numerical Methods 107
ports representing the lower and upper root boundaries, a, and b, respectively.
The exit port is attached to a Display block showing the value of the root within
the selected interval. While Figure 4.2 illustrates the plot of the two equations in
Example 4.1, the intersection of the two curves represents the root of equations
( x = 1).
The MATLAB code embeds the Simulink function of Example 4.1 as follows:
Python Solution
The following program is the Python code used to solve the two nonlinear alge-
braic equations defined in Example 4.1. Running the program yields the following
values of the two roots [3].
# Example 4.1
# importing library sympy
from sympy import symbols, Eq, solve
# defining equations
eq1 = Eq((x-y), -1) # x-y =1
eq2 = Eq((y-x**2), 1) # y-x^2=1
` g ′ ( x ) < 1 at x = x o (4.14)
where x o is the initial guess called the fixed-point iteration approach. Then the itera-
tive method is applied by successive approximation given by
x n = g ( x n − 1) (4.15)
Open Numerical Methods 109
That is
x1 = g ( x o ) , x 2 = g ( x1 ) (4.16)
g ′ ( x ) < 1 at x = x o (4.17)
x n = g ( x n − 1) (4.18)
Using the fixed-point iteration method, find the first approximate root of the fol-
lowing equation up to four decimal places.
f ( x ) = 2x 3 − 2x − 5 = 0
Solution
g ′ ( x ) < 1 at x = x o
1/ 3
2x + 5 2x + 5
x3 = → x= = g( x)
2 2
To find x o ,
−2/3
1 2x + 5
g′ ( x ) = <1
3 2
Solve
2
−
1 2x + 5 3
g′ ( x ) = <1
3 2
TABLE 4.1
The Fixed-Point Iteration Method to Solve the Equation in Example 4.2
n g ( x) x
1 2 (1.5) + 5
1/3 1.5874
2
2 2 (1.5874 ) + 5
1/3 1.5989
2
3 2 (1.5989 ) + 5
1/3 1.60037
2
4 2 (1.60037 ) + 5
1/3 1.60057
2
5 2 (1.60057 ) + 5
1/3 1.60059
2
6 2 (1.60059 ) + 5
1/3 1.600597
2
Open Numerical Methods 111
FIGURE 4.4 Simulink program uses the fixed-point iteration numerical analysis method to
solve the desired equation in Example 4.2.
Simulink Solution
The Simulink block diagram demonstrating the solution of Example 4.2 is shown in
Figure 4.4. The MATLAB code associated with the MATLAB function (available in
the Simulink/User-Defined Functions) relates to three ports, start point ( x o ), num-
ber of iterations (niter ), and the allowable error (err). The output port of the function
relates to the Display block showing the root of the desired equation.
The following program is MATLAB code that describes the solution of the non-
linear algebraic equation using the fixed-point iteration method. The following
MATLAB code is implanted in the Simulink MATLAB function.
% Example 4.2
function Res = fcn(x0,n_iter, err)
g = @(x) ((2*x + 5)/2)^(1/3);
p0 = x0; %enter initial approximation
n = n_iter; % enter no. of ierations
tol = err; %tolerance
i = 1;
p=0;
while i <= n
p = g(p0);
if abs(p-p0) < tol
break;
else
i = i+1;
p0 = p;
end
end
Res = p;
112 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Python Solution
Execution
Running the Python program produces the results shown below, where the value
of f ( x1 ) is close to zero and the discrepancy between two consecutive values is
too low.
Find the root of the following nonlinear algebraic equation using the fixed-point
iteration method.
x2 − x − 1 = 0
Support the manual calculations with the Simulink and Python programming of
the fixed-point iteration method.
Solution
1
x = 1+
x
1
x n+1 = 1 +
xn
Choose
x1 = 2
1
x1 = 1 + = 1.5
2
1 1
x2 = 1 + = 1+ = 1.666
x1 1.5
Repeat
1 1
x3 = 1 + = 1+ = 1.666
x2 1.5
1 1
x4 = 1 + = 1+ = 1.6
x3 1.666
1 1
x5 = 1 + = 1+ = 1.625
x4 1.6
1 1
x6 = 1 + = 1+ = 1.6125
x5 1.625
Simulink Solution
The fixed-point iteration method is coded with MATLAB and linked to the Simulink
MATLAB function available under the Simulink/User-Defined Functions library.
Figure 4.5 demonstrates the Simulink graphical programming using the MATLAB
function techniques. The inlet port of the MATLAB function is connected to a
114 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 4.5 Simulink block diagram utilizing the fixed-point iteration method to solve the
equation specified in Example 4.3.
constant block that shows the initial guess ( x o ), and the exit port is connected to a
Display block showing the numerical value of the calculated root.
The following program is the MATLAB code programmed for the fixed-point
iteration method in MATLAB. The code is placed in the Simulink MATLAB function.
% Exmaple 4.3
% Fixed point iteration method
function y =fcn(x0)
x=x0;
TOL = 0.001;
N = 100;
% set the iteration index
i=1;
err = 1;
% Start the iteration
while (i<N && err>TOL)
i = i +1;
x = 1 + 1/x;
err = abs (x-1-1/x);
end
% display the results
y=x;
FIGURE 4.6 Simulink solution using the Algebraic constraint block to solve the equation
specified in Example 4.3.
Python Solution
The following Python program uses the fixed-point iteration method to solve
Example 4.3. The executed results follow the program.
step = step + 1
if step > N:
flag=0
break
condition = abs(f(x1)) > e
if flag==1:
print(‘\nRequired root is: %0.8f’ % x1)
116 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 4.7 Python programming of the fixed-point iteration method to solve the equation
present in Example 4.3.
plt.plot (x1,0, ‘ro’)
plt.text(x1,-0.5, ‘The root’)
else:
print(‘\nNot Convergent.’)
After running the Python program, you should get the following results and the
plot shown in Figure 4.7.
4.4 NR METHOD
The NR method is utilized to find an approximate root of a real-valued function
( f ( x ) = 0). The method uses a continuous and differentiable function that can be
approximated by a straight-line tangent, as graphically demonstrated in Figure 4.8.
We make an initial guess for the desired root.
Open Numerical Methods 117
Find points a and b, such that a < b, and f ( a ) ⋅ f ( b ) < 0. The NR method finds the
tangent to the function f ( x ) at x = xo and extrapolates it to intersect the x-axis to get x1.
The intersection point represents the new approximation to the root, and the proce-
dure is repeated until convergence is obtained.
f ( xn )
x n+1 = x n − (4.19)
f ′ ( xn )
f ( xo )
x1 = x o − (4.20)
f ′ ( xo )
Use the NR method to find the root of the following quadratic equation.
f ( x ) = x3 − x − 1 = 0
Validate the manual root finding with Simulink and Python programming of the
NR method.
118 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Solution
The function f ( x ) ,
f ( x ) = x3 − x − 1
f ′ ( x ) = 3x 2 − 1
Find the interval where the root lies between the intervals. Try different values of x
until the function f ( x ) gets consecutive negative and positive signs.
x 0 1 2
f (x) –1 –1 5
The root lies within intervals 1 and 2. The first initial guess is
1+ 2
xo = = 1.5
2
The first iteration
Simulink Solution
With Simulink, the root can be found in two ways: the first is by using the “Algebraic
Constraint” block along with other required blocks such as Multiplication,
Constant, Sum, and Display, as illustrated in Figure 4.9. The second method uses
the Simulink “Matlab function” block available in the user-defined functions library
(Figure 4.10). The MATLAB function requires writing a MATLAB code encrypting
the NR method. The associated MATLAB program with the MATLAB function
utilizes the NR method.
TABLE 4.2
NR Method for Finding the Root of the Equation Given in Example 4.4
S. No. xo f (x0) f’ (xo) xi
1 1.5 0.875 5.75 1.3478
2 1.3478 0.10068 4.44991 1.3252
3 1.3252 0.00206 4.26847 1.3247
4 1.3247 0 4.26463 1.3247
Open Numerical Methods 119
FIGURE 4.9 Root finding using the Simulink Algebraic constraint block to solve the qua-
dratics equations defined in Example 4.4.
FIGURE 4.10 Simulink block diagram utilizing the MATLAB function and NR method
representing the solution of the equation defined in Example 4.4.
120 Numerical Methods in Chemical Engineering Using Python® and Simulink®
% Example 4.4
function y = fcn(x, x_old)
%x = initial guess;
%x_old = previous x;
iter = 0;
while abs(x_old-x) > 10^-3 && x ~= 0
x_old = x;
x = x - (x^3- x-1)/(3*x^2-1);
iter = iter + 1;
end
y=x;
Python Solution
The following program is the Python code that uses the NR method to solve
the quadratic equation in Example 4.4. The program is followed by the results
implemented.
# Example 4.4
# Newton Raphson
# The function is x^3- x -1
def func(x):
return x**3- x -1
# Derivative of the above function
def derivFunc(x):
return 3 * x**2-1
# Function to find the root
def newtonRaphson(x):
h = func(x) / derivFunc(x)
while abs(h) >= 0.0001:
h = func(x)/derivFunc(x)
Execution result:
Find the root of the following quadratic nonlinear algebraic equation using the NR
approach, and an initial guess value equals 4.
f (x) = x2 − 7
Confirm the manual root finding with Simulink and Python programming of the
NR method.
Open Numerical Methods 121
TABLE 4.3
Solution of Example 4.5 Using the NR Method
S. No. xo f(x0) f’(xo) xi
1 4.00000 9.00000 8.00000 2.87500
2 2.87500 1.26560 5.75000 2.65489
3 2.65489 0.04844 5.30978 2.64577
4 2.64577 0.0000832 5.29153 2.64575
Solution
f ′ ( x ) = 2x
f ( x0 ) 42 − 7 9
x1 = x o − = 4− = 4 − = 2.875
f ′ ( xo ) 2(4) 8
f ( x1 ) 2.8752 − 7 1.266
x 2 = x1 − = 2.875 − = 2.875 − = 2.655
f ′ ( x1 ) 2 ( 2.875) 5.75
Repeat the iterations until the value of xi is almost constant, as shown in Table 4.3.
The table shows that after four iterations, the value of 2.64575 is the approximate
value of one of the roots.
Simulink Solution
Figure 4.11 is the Simulink block diagram utilizing NR’s method for solving the
equation required in Example 4.5. The MATLAB code incorporated the MATLAB
function block as follows.
The following MATLAB code built into the MATLAB function block is pro-
grammed in the NR method to solve the equation specified in Example 4.5.
%Example 4.5
function y = fcn(x, x_old)
%x = initial guess;
%x_old = previous x;
iter = 0;
while abs(x_old-x) > 10^-3 && x ~= 0
x_old = x;
x = x - (x^2–7)/(2*x);
iter = iter + 1;
end
y=x;
122 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 4.11 Simulink block diagram utilizing the NR method to solve of equation defined
in Example 4.5.
Python Solution
The below program is written in Python, employing the NR method to solve the
nonlinear algebraic equation defined in Example 4.5. The implementation result
follows the program.
# Example 4.5
# Newton Raphson
# The function is x^3- x -1
def func(x):
return x**2–7
# Derivative of the above function
def derivFunc(x):
return 2 * x
# Function to find the root
def newtonRaphson(x):
h = func(x) / derivFunc(x)
while abs(h) >= 0.0001:
h = func(x)/derivFunc(x)
Open Numerical Methods 123
4.5 NR MULTIVARIABLE
The multivariate NR method directly extends the single variable method. While the
single variable method solves a single equation of the form f ( x ) = 0, the multivariate
version solves a system of more than one equation of the form
f1 ( x1 , x 2 , x3 ,…, x n−1 , x n ) = 0
f2 ( x1 , x 2 , x3 ,…, x n−1 , x n ) = 0
f3 ( x1 , x 2 , x3 ,…, x n−1 , x n ) = 0
fn ( x1 , x 2 , x3 ,…, x n−1 , x n ) = 0
Consider the system of two nonlinear algebraic equations. Find the values of the
unknown variables using the multivariate NR method.
2x 3 + 8x − 4 y = 4
4x − 3 y − y 2 = 1
Validate the manual root finding with Simulink and Python programming of the
multivariate NR method.
Solution
f1 ( x , y ) = 4 − 8 x − 2 x 3 + 4 y = 0
f2 ( x , y ) = 1 − 4 x + 3 y + y 2 = 0
−1
∂ f1 ∂ f1
k +1 k f1
k
x x ∂x ∂y
= −
y y ∂ f2 ∂ f2 f
2
∂x ∂y
124 Numerical Methods in Chemical Engineering Using Python® and Simulink®
k +1 k −1 k
x 0.5 −8 − 6 x 2 4 f1
= −
y 0.5 −4 3 + 2 y f2
0.5,0.5
−1
x 0.5 −8 − 6x 2 4 1.75
y = −
0.5 −4 3 + 2y 0.75
−1
x 0.5 −9.5 4 1.75
y = −
0.5 −4 4 0.75
x 0.5 1 4 −4 1.75
y = −
0.5 22 4 −9.5 0.75
1
x = 0.5 + ( 4 × 1.75 − 4 × 0.75) = 0.6818
22
1
y = 0.5 + ( 4 × 1.75 − 9.5 × 0.75) = 0.4943
22
Simulink Solution
Figure 4.12 presents the Simulink block diagram for solving Example 4.6 using the
Simulink Algebraic constraint block.
Python Solution
The following Python program shows how to use the NR algorithm to find the
roots of a multivariate system of equations. The NR algorithm is relatively simple
and very powerful for finding the roots of a real-valued function that has a continu-
ous derivative within a given range
x_last = x_init
for k in range(max_iter):
# Stop condition:
if np.linalg.norm(diff) < epsilon:
print(‘\nNumber of iterations:’, k)
break
else: # only if the for loop end ‘naturally.’
print(‘not converged’)
return x_last
# Results:
xy_sol = iter_newton(func_Ex, [1.0,2.0], jacobian_Ex)
print(‘\nSolution (roots)\n [x, y]:\n’, xy_sol)
print(‘\nresubstitution of the roots\n [f(x), f(y)]:\n’,
func_Ex(xy_sol))
Execution results:
Number of iterations: 5
Solution (roots)
126 Numerical Methods in Chemical Engineering Using Python® and Simulink®
[x, y]:
[0.66520106 0.47757534]
resubstitution of the roots
[f(x), f(y)]:
[-8.881784197001252e-16, -1.1102230246251565e-16]
xi − xi −1
xi +1 = xi − f ( xi ) (4.22)
f ( xi ) − f ( xi −1 )
x1 − x 0
x 2 = x1 − f ( x1 ) (4.23)
f ( x1 ) − f ( x o )
In general, applying a backward approximation, the secant algorithm to find the root
becomes
( xn−1 − xn−2 )
x n = x n−1 − f ( x n−1 ) (4.24)
f ( x n−1 ) − f ( x n− 2 )
FIGURE 4.13 Graphical explanation of the numerical root finding using the secant method.
Open Numerical Methods 127
for i = 2,
( x1 − x0 )
x 2 = x1 − f ( x1 ) (4.25)
f ( x1 ) − f ( x 0 )
Figure 4.13 is a graphical demonstration of the secant method for root finding. The
method is like the bisectional method, which divides each interval by choosing the
midpoint; in contrast, the secant method divides each interval by the secant line con-
necting the endpoints. Providing that f ( x ) is continuous on [a, b] and f ( a ) f ( b ) < 0,
the secant method always converges to a root for f ( x ) = 0. Considering the connec-
tion of the endpoint values ( a, f ( a )) and ( b, f ( b )). The line connecting these two
points is called the secant line (Figure 4.14) and is given by the following formula:
f (b) − f (a)
y= ( x − a) + f (a) (4.26)
b−a
f (b) − f (a)
0= ( x − a) + f (a) (4.27)
b−a
Solving for x
b−a
x = a − f (a) (4.28)
f (b) − f (a)
128 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Compute the following function in two iterations using the secant method, in
which the real roots of the equation f ( x ) lie in the interval (0,1).
f ( x ) = x 3 − 5x + 1 = 0
Confirm the manual rooting find process using Simulink and Python programming
of the secant method.
Solution
x o = 0, f ( x 0 ) = f ( 0 ) = 1
x1 = 1, f ( x1 ) = f (1) = −3
Hence,
( x1 − xo ) (1 − 0 )
x 2 = x1 − f ( x1 ) = 1 − f (1)
f ( x1 ) − f ( x o ) f (1) − f ( 0 )
(1 − 0 ) 1
x2 = 1 − f (1) = 1 − ( −3) = 0.25
f (1) − f ( 0 ) −3 − 1
FIGURE 4.15 Simulink block diagram using the secant method describing the solution of
the equation defined in Example 4.7.
Simulink Solution
Figure 4.15 is the Simulink block diagram representing the solution of the equation
specified in Example 4.7. The MATLAB code follows the diagram representing the
Secant method implants in the Simulink MATLAB function.
The embedded MATLAB code programmed the secant method to solve the
equation defined in Example 4.7.
% Example 4.7
function y = fcn(a, b, n)
f=@(x)(x^3–5*x + 1);
xn1=a;
xn2=b;
xn = (xn2*f(xn1) - xn1*f(xn2))/(f(xn1) - f(xn2));
k = 0;
while (k < n)
k = k + 1;
xn2 = xn1;
xn1 = xn;
xn = (xn2*f(xn1) - xn1*f(xn2))/(f(xn1) - f(xn2));
end
y = xn;
Python Solution
The following is the Python code utilizing the secant method in solving the equa-
tion specified in Example 4.7.
# Example 4.7
# The Secant method function (SM)
130 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 4.16 Python solution using the secant method of the equation defined in
Example 4.7.
import numpy as np
import matplotlib.pyplot as plt
# Our f(x) function
def f(x):
y = x**3–5*x + 1
return y
The data generated from running the Python code is plotted in Figure 4.16.
Using the secant method, compute the root of the equation in the interval [0, 1].
Make sure that the root should be correct to three decimal places.
f ( x ) = x 3 − 5x + 1 = 0
Validate the manual root finding with Simulink and Python programming of the
secant method for a cubic equation.
Open Numerical Methods 131
Solution
x o = 0, f ( x o ) = 1, x1 = 1, f ( x1 ) = −3
x 0 − x1
x 2 = x1 − f ( x1 )
f ( x o ) − f ( x1 )
Substitute
0 −1
x2 = 1 − ( −3) = 0.25
1 − ( −3)
f ( x 2 ) = −0.234375
x1 − x 2
x3 = x 2 − f ( x2 )
f ( x1 ) − f ( x 2 )
1− 0.25
x3 = ( −0.234375) − ( −0.234375) = 0.186441
−3− ( −0.234375)
x 2 − x3
x 4 = x3 − f ( x3 )
f ( x 2 ) − f ( x )
3
0.25 − 0.186441
x 4 = 0.186441 − ( −0.234375) = 0.201736
( −0.234375 ) − ( 0.074276 )
x 4 − x5
x5 = x 4 − f ( x4 )
f ( x 4 ) − f ( x 5 )
Substitute the old x 4
0.186441 − 0.201736
x5 = 0.201736 − ( −0.00470 ) = 0.201640
0.074276 − − ( −0.00470 )
Simulink Solution
The Secant method followed by the implanted MATLAB coded in MATLAB func-
tion is presented in the Simulink graphical programming shown in Figure 4.17.
132 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 4.17 Secant method for the solution of the equation defined in Example 4.8.
The following program is the MATLAB code encrypting the secant method and
is associated with the Simulink MATLAB function block.
function y = fcn(x0,x1)
% Secant Method in MATLAB
f=@(x)x^3–5*x+1; % Roots of the function;xA3–5*x+l
tol = 0.001; % tolerance
itr=1000;%nurnber of iteration
for i=1:itr
x2=(x0*f(x1)-x1*f(x0))/(f(x1)-f(x0));
if abs(x2-x1)<tol
break;
else
x0=x1;
x1=x2;
end
end
y=x2;
The following root is obtained using the Math operation/Algebraic constraint func-
tion from the Simulink library with an initial guess of zero (Figure 4.18).
Python Solution
The following Python program utilizes the secant method coded to solve the equa-
tion defined in Example 4.8.
# Example 4.8
# Implementation of SECANT METHOD
# Defining Function
Open Numerical Methods 133
FIGURE 4.18 Simulink solution using the Algebraic constraint block of the equation
defined in Example 4.8.
def f(x):
return x**3–5*x + 1
Execution results:
Secant Method
===============================
The required root is: 0.20162848
134 Numerical Methods in Chemical Engineering Using Python® and Simulink®
The equation of the second-degree polynomial through the three points is:
g ( x ) = c + b ( x − x2 ) + a ( x − x2 )
2
(4.29)
f ( x1 ) − f ( x o )
δo = (4.30)
x1 − x o
f ( x 2 ) − f ( x1 )
δ1 = (4.31)
x2 − x1
ho = x 2 − x o (4.32)
h1 = x1 − x 2 (4.33)
δ1 − δ o
a= (4.34)
h1 + ho
b = ah1 + δ 1 (4.35)
c = f ( x2 ) (4.36)
−2c
x3 = x1 + (4.37)
b ∓ b 2 − 4ac
x3 − x 2
ε= 100% (4.38)
x3
136 Numerical Methods in Chemical Engineering Using Python® and Simulink®
x 3 − 13x − 12 = 0
Solution
f ( x 0 ) = f ( 4.5) = 20.626
f ( x1 ) = f ( 5.5) = 82.875
f ( x 2 ) = f ( 5) = 48.0
ho = x1 − x 0 = 5.5 − 4.5 = 1
h1 = x 2 − x1 = 5 − 5.5 = −0.5
f ( x1 ) − f ( x o ) 82.875 − 20.625
δo = = = 62.25
( x1 − xo ) 5.5 − 4.5
f ( x1 ) − f ( x 2 ) 82.875 − 48
δ1 = = = 69.75
( x1 − x2 ) 5.5 − 5.0
δ 1 − δ o 69.75 − 62.25
a= = = 15
h1 + ho 1 + ( −0.5)
c = f ( x 2 ) = 53 − 13( 5) − 12 = 48
−2c −2 ( 48 )
x3 = x1 + = 5+ = 3.976
b ∓ b 2 − 4ac 62.25 ∓ ( 62.25)2 − 4 (15)( 48)
The percentage error is:
3.976 − 5
ε= 100% = 25.79%
3.976
Simulink Solution
Using Muller’s method to build the Simulink block diagram representing the solu-
tion of the equation defined in Example 4.9 is shown in Figure 4.20. The MATLAB
code follows the Simulink graphical solution implanted in the MATLAB function
programs, the Muller method. The MATLAB function is connected to three input
ports representing the three constants containing the three initial guesses.
Open Numerical Methods 137
FIGURE 4.20 Simulink block diagram using the Muller method to solve the equation
defined in Example 4.9.
The following are the MATLAB codes implanted in the MATLAB function of
Example 4.9.
% Example 4.9
function y = fcn (p0, p1, p2)
TOL = 10^-5;
NO = 100;
f =@ (x) x^3–13*x-12; % the required function
h1 = p1- p0; h2 = p2- p1;
DELTA1 = (f(p1) - f(p0))/h1;
DELTA2=(f(p2) - f(p1))/h2;
d = (DELTA2- DELTA1)/(h2 + h1);
i=3;
p=0;
while i <= NO
b = DELTA2 + h2*d;
D = (b^2–4*f(p2)*d)^(1/2);
if abs(b-D) < abs(b+D)
E = b + D;
else
E = b - D;
end
h = -2*f(p2)/E; p=p2+h;
if abs(h) < TOL
break
end
p0 = p1; p1= p2; p2 = p;
h1 = p1- p0; h2 = p2- p1;
DELTA1 = (f(p1) - f(p0))/h1;
DELTA2 = (f(p2) - f(p1))/h2;
d = (DELTA2- DELTA1)/(h2 + h1); i = i + 1;
end
y = p;
138 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Python Solution
The solution of Example 4.9 using Muller’s method programmed with Python is
shown as follows:
# Initial guesses
a = 4.5
b = 5.5
c = 5
Muller(a, b, c)
Execution result:
4.8 SUMMARY
There are various methods available to find the roots of equations. The simplest
method is the bisection method. The method is based on the changes in sign of a
function in the vicinity of a root. NR is based on using an initial guess for the root
and finding the intersection with the straight-line axis representing the slope at the
initial guess. Based on a reasonable estimate of the initial guess, the method works
and converges extremely fast.
4.9 PROBLEMS
1. Solving the following two equations using the substitution method.
x − 2y = 8
x+y=5
Answer: (x = 6, y = −1)
2. Solve the following two equations using the method of substitution.
2 x + 3 y + 15 = 0
x + 4y + 2 = 0
y = 2x + 8
y = 5x − 1
4. Solve the following two linear algebraic equations using the substitution
method.
19 2
y= − x
5 5
y = 3( x − 1)
Answer: (x = 2, y = 3)
5. Find the roots of the following nonlinear algebraic equation using the fixed-
point iteration method.
x 2 − 2x − 3 = 0
Answer: (x = 3)
2x 3 − 11.7 x 2 + 17.7x − 5 = 0
Answer: (x = 0.365)
x 3 − 3x − 5 = 0
Answer: (x = 2.279)
x 3 − 2x 2 + x − 3 = 0
Answer: (x = 2.174)
x 2 + xy − 10 = 0
y + 3 xy 2 − 57 = 0
10. Find the roots of the following equation using Muller’s method, starting
with the initial approximations as x o = 2, x1 = 2.5, x 2 = 3
x 3 − 3x − 5 = 0
Answer: 2.279
f ( x ) = x 3 + 2 x 2 + 10 x − 20 = 0
Answer: 1.368
x 5 − 5x + 2 = 0
Answer: 1.372
REFERENCES
5 Initial Value Problem
Differential Equations
An initial value problem (IVP) is an ordinary differential equation (ODE) with an
initial condition that specifies the value of the unknown function at a given point
in the domain. Numerical methods are essential for solving system IVPs in ODEs,
especially in complicated cases. This chapter introduces eigenvalue, eigenvector, and
elimination techniques to solve systems of more than one initial value ODEs.
LEARNING OBJECTIVES
1. Solve IVP using eigenvalue and eigenvector technique.
2. Apply elimination techniques to solve initial value problems (IVPs).
3. Master the use of the Simulink Integrator block in designing and simulating
dynamic systems.
4. Utilize Python programming language to address an IVP.
5.1 INTRODUCTION
In mathematics, an ODE is a differential equation that contains one or more functions
of one independent variable and the derivatives of those functions. The term ordinary
is used in contrast to the partial differential equation, which may concern more than
one independent variable. ODEs may represent system dynamics in transferring heat
and mass and related problems in chemical engineering and other engineering disci-
plines. The IVP describes the behavior of a system due to certain disturbances that
cause the system to deviate from its steady-state value. Differential equations can
arise naturally from physical modeling. The following IVP describes the concentra-
tion profile of three chemicals in a reactor as a function of time. The following set of
ODEs represents certain dynamic equations [1].
dc1
= f1 ( c1 ……c3 )
dt
dc2
= f2 ( c1 ……c3 )
dt
dc3
= fn ( c1 ……c3 )
dt
dC
= f (c )
dt
0 = f1 ( c1 ……c3 )
0 = f2 ( c1 ……c3 )
0 = fn ( c1 ……c3 )
The solution method is the same as the single first-order ODE solution method and
can be extended to multiple ODEs system.
Ax = λ x
Ax − λ x = 0
Ax − λ Ix = 0
( A − λI ) x = 0
A − λI = 0
Solve the following two ODEs simultaneously using the eigenvalue and eigenvec-
tor technique.
dy1
= −3 y1 + 2 y2 , y1 ( 0 ) = 1
dt
dy2
= y1 − 2 y2 , y2 ( 0 ) = 0
dt
Manual Solution
First, convert the system into matrix form. The equations can be written as follows:
dY
= AY
dt
where
−3 2
A=
1 −2
A − λI = 0
−3 2 λ 0 −λ − 3 2
− = =0
1 −2 0 λ 1 −2 − λ
−λ − 3 2
det = ( − λ − 3) ( −2 − λ ) − (1)( 2 ) = 0
1 −2 − λ
Rearrange
λ 2 + 5λ + 6 − 2 = λ 2 + 5λ + 4 = 0
Factorize
( λ + 4 )( λ + 1) = 0
−3 2 x11 x11
λ1 = −1 : = −1
1 −2 x12 x
12
x11 = x12
Accordingly,
1
X1 =
1
−3 2 x 21 x 21
λ2 = −4 : = −4
1 −2 x 22 x
22
−3 x 21 + 2 x 22 = −4x 21
x 21 − 2 x 22 = −4 x 22
−2 x 21 = −4 x 21 − 4x 22
Simplify
2 x 21 = −4 x 22
Hence,
x 21 = −2x 22
−2
X2 =
1
In another format,
y1 1 ( −1t ) −2 −4t
= c1 e + c2 e
y 1 1
2
The solution is
y1 = c1e − t − 2c2 e −4 t
y2 = c1e − t + c2 e −4 t
1 = c1 − 2c2
0 = c1 + c2
1 1
c1 = , c2 = −
3 3
1 −2 1
y1 = e − 2 − e −8 = 0.0453
3 3
1 −2 1 −8
y2 = e − e = 0.045
3 3
Simulink Solution
Figure 5.1 represents the Simulink block diagram using the Simulink Integrator
block for solving the two ODEs defined in Example 5.1. The integrator’s default
numerical integration method is the fourth-order Runge-Kutta method.
An alternative way is to use the MATLAB function block available in the User-
Defined Functions of the Simulink library. The MATLAB function is associated
with a program written in MATLAB programming language. The solution using
the eigenvalue and eigenvector approaches of the two ODEs specified in Example
5.1 is presented by the Simulink block diagram shown in Figure 5.2. The Simulink
block diagram is followed by the MATLAB code associated with the MATLAB
function. The predicted approximate results are identical to the case using the
Integrator block and the default RK4. The MATLAB function input port relates to a
constant (n), representing the independent variable’s simulation stop time (t). The
exit ports are connected with two Display blocks for the output of y1 and y2 at
the simulation stop time. The change in the dependent variable ( y1 , y2 ) versus the
independent time variable (t ) is presented in Figure 5.3.
The following program represents the MATLAB code implanted in the MATLAB
function shown in Figure 5.2. The results are plotted in Figure 5.3.
148 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 5.1 Solution using the Simulink integrator block and the fourth-order Runge-
Kutta approach of equations defined in Example 5.1.
FIGURE 5.2 Simulink solution using the eigenvalue and eigenvector approach of ODEs
defined in Example 5.1.
Initial Value Problem Differential Equations 149
FIGURE 5.3 Simulink generates a plot of the two ODEs defined in Example 5.1.
% Example 5.1
function [Res1,Res2] = fcn(n)
% The coefficients of the Matrix
A = [-3 2;
1 -2];
% Calculating the eigenvalue and eigenvectors
[V, D] = eig(A);
% initial conditions
Y0 = [1; 0];
% Calculating the constants C1 and C2
c = diag(V\Y0);
t = linspace(0,n);
T = [t;t];
y = V*c*exp(D*T);
plot(t, y, ‘LineWidth’, 1.5))
xlabel(“Time”)
ylabel(“y “, rotation=0)
grid on
str = ‘\leftarrow y_1’;
text(0.2,0.6,str)
str2 = ‘\leftarrow y_2’;
text(0.2,0.1,str2)
Res1 = y(1,end);
Res2 = y(2,end);
Python Solution
The following program is a Python code that uses the eigenvalue and eigenvector
approaches to solve the two ODEs equations given in Example 5.1. The plot of y1
and y2 versus time (t) is presented in Figure 5.4.
150 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 5.4 Plot of y1 and y2 versus time (t) generated by the Python program using eigen-
value and eigenvector represents the solution of two ODEs defined in Example 5.1.
# Example 5.1
import numpy as np
import matplotlib.pyplot as plt
A = np.array([[-3,2], [1,-2]])
# extract eigenvalues
[w, v]= np.linalg.eig(A)
y10 = 1
y20 = 0
Pinitial = np.array([y10, y20])
C1, C2 = np.linalg.solve(v, Pinitial)
# combine everything to get the solution to P1
#t = np.linspace(0,2)
fig = plt.figure()
t=np.linspace(0,2,100)
y1 = C1 * np.exp(w[0]*t)*v[0,0] + C2 * np.exp(w[1] * t) * v[0,1]
y2 = C1 * np.exp(w[0]*t)*v[1,0] + C2 * np.exp(w[1] * t) * v[1,1]
#plt.plot(t, y1, t, y2)
plt.plot(t, y1, ‘-r’, label=’y1’)
plt.plot(t, y2, ‘:b’, label=’y2’)
plt.grid(True)
plt.ylabel(“y”, rotation =0)
plt.xlabel(“Time”)
plt.legend()
Calculate the eigenvalue and eigenvector for the following two ODEs.
dy1
= y2 , y1 ( 0 ) = 1
dt
dy2
= −2 y1 − 3 y2 , y2 ( 0 ) = 0
dt
Initial Value Problem Differential Equations 151
Solve the two ODEs manually and support the manual solution using the Simulink/
MATLAB programming and Python programming of the eigenvalue and eigenvec-
tor approaches.
Solution
0 1
A=
−2 −3
A − λI = 0
0 1 1 0 0 1 λ 0 0−λ 1
−λ = − =
−2 −3 0 1 −2 −3 0 λ −2 −3 − λ
a b
A = = ad − bc
c d
Accordingly,
0−λ 1
= ( 0 − λ ) ( −3 − λ ) − ( −2 )(1) = 0
−2 −3 − λ
Simplify
λ 2 + 3λ + 2 = ( λ + 2 ) ( λ + 1) = 0
λ1 = −1, λ2 = −2
A. X1 = λ1 . X1
( A − λ1 ) .X1 = 0
0 1 λ1 0 − λ1 1
− .X1 = . X1 = 0
−2 −3 0 λ1 −2 −3 − λ1
1 1 1 1 x11
.x1 = . =0
−2 −2 −2 −2 x12
x11 + x12 = 0
Accordingly,
x11 = −x12
−2 x11 − 2 x12 = 0
x11 = −x12
The eigenvector
x11 −1
X1 = =
x12 1
We find that the first eigenvector is any vector composed of two components
where the two components have the same magnitude and opposite signs. Follow
the same procedure to determine the eigenvector for the second eigenvalue
(λ2 = −2):
A. X 2 = λ2 . X 2
Rearrange
( A − λ2 ) . X 2 = 0
0 1 λ2 0
− . X 2 = 0
−2 −3 0 λ2
Initial Value Problem Differential Equations 153
0 − λ2 1− 0
. X 2 = 0
−2 − 0 −3 − λ2
2 1 2 1 x 21
−2 .X1 = . =0
−1 −2 −1 x 22
Multiply the first row in the first matrix with the first column of the second matrix
2 x 21 + x 22 = 0
Rearrange
2x21 = − x22
Accordingly,
−1
X2 =
2
Again, the eigenvector’s choice of –1 and 2 was arbitrary; Only their proportion is
essential. The general solution is
In another format,
y1 ( −1t ) −1 −2 t −1
= c1e + c2 e
y 1 2
2
The solution is
y1 = −c1e − t − c2 e −2t
The values of c1 and c2 can be determined using the initial condition of y1 and y2
1 = c1e −0 − c2 e −2( 0 )
Simplifying,
1 = −c1 − c2
0 = c1 + 2c2
c1 = −2
c2 = 1
Accordingly,
−1 − t −1 −2t
Y = −2 e + 1 e
1 2
y1 = −2e − t − e −2t
y2 = 2e − t + 2e −2t
When t = 2
y1 = 2e −2 − 1e −2( 2) = 0.25235
y2 = 2e −( 2) + 2e −2( 2) = −0.23404
Simulink Solution
Figure 5.5 is the Simulink block diagram representing the solution of the two
nonlinear ODEs equations defined in Example 5.2. The following program is the
MATLAB code utilizing the eigenvalue and eigenvector approach associated with
the Simulink MATLAB function block dragged from the User-Defined Functions
Simulink library. The MATLAB function input port is connected with a constant
(n), representing the simulation end time. The output port is connected with two
Display blocks that yield the values of dependent variables at the simulation stop
time.
The following program signifies the MATLAB code implanted in the MATLAB
function present in Figure 5.5. The program uses eigenvalue and eigenvector
methodology to solve the two ODEs defined in Example 5.2.
% Example 5.2
function [Res1,Res2] = fcn(n)
% The coefficients of the Matrix
A = [0 1;
-2 -3];
% Calculating the eigenvalue and eigenvectors
Initial Value Problem Differential Equations 155
FIGURE 5.5 The Simulink block diagram using the eigenvalue and eigenvector approach
of two ODEs defined Example 5.2.
[V, D] = eig(A);
% initial conditions
Y0 = [1; 0];
% Calculating the constants C1 and C2
c = diag(V\Y0);
t = linspace(0,n);
T = [t;t];
y = V*c*exp(D*T);
% Plot sextion
plot(t, y, ‘LineWidth’, 1.5)
xlabel(“Time”)
ylabel(“y “, rotation=0)
grid on
str1 =’\leftarrow y_1’;
str2 = ‘\leftarrow y_2’;
text (0.65,0.8,str1,’Color’, ‘b’, ‘FontSize’, 15);
text (0.4,-0.4,str2,’Color’, ‘r’, ‘FontSize’, 15);
ylim([-0.6 1]);
Res1 = y(1,end);
Res2 = y(2,end);
Executing the described Simulink block diagram generates the plot shown in
Figure 5.6.
Python Simulation
The following program is a Python code that simultaneously uses the eigenvalue and
eigenvector approaches to solve the two nonlinear equations given in Example 5.2.
Running the Python program generates the data plotted in Figure 5.7.
156 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 5.6 Plot of y1 and y2 versus time (t) using eigenvalue and eigenvector in MATLAB
of the two equations defined in Example 5.2.
FIGURE 5.7 Plot of y1 and y2 versus time (t) utilizing the eigenvalue and eigenvector
approach programmed in Python of the two equations described in Example 5.2.
# Example 5.2
import numpy as np
import matplotlib.pyplot as plt
A = np.array([[0,1], [-2,-3]])
# extract eigenvalues
[w, v]= np.linalg.eig(A)
y10 = 1
y20 = 0
Pinitial = np.array([y10, y20])
C1, C2 = np.linalg.solve(v, Pinitial)
Initial Value Problem Differential Equations 157
dy1
= 2y1 + y2 , y1 ( 0 ) = 1
dx
dy2
= 3y1 , y2 ( 0 ) = 0
dt
Solution
dY 2 1 1
= AY = Y , Yo =
dt 3 0
0
Using the identity matrix (I) and the eigenvalue (λ ), first, we will determine the
eigenvalues of matrix A
AX = λ X
Rearrange
AX − λ X = ( A − λ I ) X = 0
2 1 λ 0
− X = 0
3 0 0 λ
2−λ 1
=0
3 0−λ
158 Numerical Methods in Chemical Engineering Using Python® and Simulink®
2−λ 1
det =0
3 0−λ
( 2 − λ )( − λ ) − (3)(1) = 0
Simplify
λ 2 − 2λ − 3 = 0
Factorize
( λ − 3)( λ + 1) = 0
λ1 = 3, λ2 = −1
2 − λ1 1 x11 0
=
3 − λ1 x12 0
Substitute λ1 = 3
−1 1 x11 0
3 =
−3 x12 0
−x11 + x12 = 0
x11 1
X1 = =
x12 1
1
The eigenvector of λ1 is
1
Eigenvector X 2 of λ2 = −1
2 − λ2 1 x 21 0
=
3 − λ2 x 22 0
Initial Value Problem Differential Equations 159
Substitute λ2 = −1
2 − ( −1) 1 x 0
21 =
3 − ( −1) x 22 0
3 1 x 21 0
=
3 1 x 22 0
3 x 21 + 1x 22 = 0
If we assume x 21 = 1, then x 22 = −3
1
According to the eigenvector for λ2 is
−3
The eigenvector matrix is
1 1
X=
1 −3
The solution
y1 ( λ1t ) 1 λ2 t
1
= c1e + c2 e
2
y
1
−3
y1 = c1e3t + c2 et
y2 = c1e3t − 3c2 et
y1 ( 0 ) = 1, y2 ( 0 ) = 0
1 = c1 + c2 (5.1)
0 = c1 − 3c2 (5.2)
1 − 0 = c1 − c1 + c2 − ( −3c2 ) = 4c2
160 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Accordingly,
1 3
c2 = , c1 =
4 4
3 3t 1 t
y1 = e + e
4 4
3 3t 3 t
y2 = e − e
4 4
Simulink Solution
Figure 5.8 shows the Simulink block diagram representing the solution of the two
ODEs defined in Example 5.3 using the Integrator block dragged from the most
Simulink commonly used library. Figure 5.9 is obtained by double-clicking the
Scope. To change the color of the plot generated by the Scope, click on view/style
and change the Figure color to white and the axis background color to white. The
figure should be like that in Figure 5.9.
The Simulink block diagram describes the solution using the eigenvalue and
eigenvector of the two ODEs defined in Example 5.3, shown in Figure 5.10. The
input port of the MATLAB function (dragged from the User-Defined Functions in
the Simulink library) is connected with a constant (n), representing the simulation
end time. The two outlet ports are connected with two Display blocks to yield the
dependent variable values ( y1 , y2 ) at the end period of the independent variable (t ).
FIGURE 5.8 Simulink solution using the Integrator block to solve simultaneously the two
ODEs defined in Example 5.3.
Initial Value Problem Differential Equations 161
FIGURE 5.9 Plot generated by double-clicking the scope in the Simulink block diagram
represents the solution of the two ODEs defined in Example 5.3.
FIGURE 5.10 Simulink block diagram using eigenvalue and eigenvector of the two ODEs
described in Example 5.3.
% Example 5.3
function [Res1,Res2] = fcn(n)
% The coefficients of the Matrix
A = [2 1;
3 0];
% Calculating the eigenvalue and eigenvectors
[V, D] = eig(A);
162 Numerical Methods in Chemical Engineering Using Python® and Simulink®
% initial conditions
Y0 = [1; 0];
% Calculating the constants C1 and C2
c = diag(V\Y0);
t = linspace(0,n);
T = [t;t];
y = V*c*exp(D*T);
% plot section
plot(t, y, ‘LineWidth’, 1.2)
xlabel(“Time”, “FontSize”, 15)
ylabel(“y”, ‘rotation’, 0,’FontSize’, 15)
ylim([0 16]);
grid on;
str1 = ‘\leftarrow y_2’;
str2 = ‘y_1 \rightarrow’;
text (0.6,4,str1,’color’, ‘b’, ‘FontSize’, 15);
text (0.65,7.5,str2,’color’, ‘r’, ‘FontSize’, 15);
% displayed results
Res1 = y(1,end);
Res2 = y(2,end);
The result of Example 5.3 generated by Simulink using the eigenvalue and eigen-
vector approach is shown in Figure 5.11.
Python Solution
FIGURE 5.11 Simulink solution of the binary differential equations defined in Example 5.3
using the eigenvalue and eigenvector approach.
Initial Value Problem Differential Equations 163
FIGURE 5.12 Python solution using eigenvalue and eigenvector technique of the two equa-
tions described in Example 5.3.
# Example 5.3
import numpy as np
import matplotlib.pyplot as plt
A = np.array([[2,1], [3,0]])
# extract eigenvalues
[w, v]= np.linalg.eig(A)
y10 = 1
y20 = 0
Pinitial = np.array([y10, y20])
C1, C2 = np.linalg.solve(v, Pinitial)
# combine everything to get the solution to P1
#t = np.linspace(0,2)
fig = plt.figure()
t=np.linspace(0,1,100)
y1 = C1 * np.exp(w[0]*t)*v[0,0] + C2 * np.exp(w[1] * t) * v[0,1]
y2 = C1 * np.exp(w[0]*t)*v[1,0] + C2 * np.exp(w[1] * t) * v[1,1]
#plt.plot(t, y1, t, y2)
plt.plot(t, y1, ‘-b’, label=’y1’)
plt.plot(t, y2, ‘:r’, label=’y2’)
plt.grid(True)
plt.ylabel(“y “, rotation=0)
plt.xlabel(“Time”)
plt.legend()
d
1. Replace derivatives with D.
d ( indep )
164 Numerical Methods in Chemical Engineering Using Python® and Simulink®
2. Rearrange the equations such that they start with x and follows by y.
3. Solve by eliminating Dx or Dy.
4. Solve the differential equation.
5. Solve the other equation following the steps.
6. Eliminate constants using boundary conditions.
Solve the following two ODEs simultaneously using the elimination method.
dy
= −9x
dt
dx
= −4y
dt
Solution
Dy = −9x
Dx = −4y
Dy + 9 x = 0
4y + Dx = 0
3. Start the elimination process. Multiply the first equation by D and the
second equation by 9.
D 2 y + 9 Dx = 0
36y + 9 Dx = 0
D 2 y − 36y = 0
a 2 e at − 36e at = 0.
Initial Value Problem Differential Equations 165
a 2 − 36 = 0
a = ∓6
Accordingly,
y = c16t + c2 e −6t
Dy + 9 x = 0
4y + Dx = 0
4 Dy + 36 x = 0
4Dy + D 2 x = 0
D 2 x − 36x = 0
Let x = ae at
a 2 e at − 36e at = 0
Divide by e at
a 2 − 36 = 0
a = ∓6
x = c1e6t + c2 e −6t
dx
= 4 x − 3y
dt
dy
= 6x − 7 y
dt
166 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Solution
d
Replace derivatives , with D. In other words, write in differential nota-
d ( indep )
tion (D).
Dx = 4 x − 3 y
Dy = 6 x − 7 y
Move all terms with dependent variables to the left-hand side and arrange columns
by variables.
( D − 4 ) x + 3y = 0
−6 x + ( D + 7 ) y = 0
Start the elimination process by eliminating x. Multiply the first equation by 6 and
the second by ( D − 4 ) as follows:
6 x ( D − 4 ) + 18y = 0
−6 x ( D − 4 ) + ( D − 4 )( D + 7 ) y = 0
(
18y + D 2 + 3 D − 28 y = 0 )
Divide both sides by y and rearrange
D 2 + 3 D − 10 = 0
( D − 2)( D + 5) = 0
d
D= = 2 or − 5
dt
Accordingly,
y ( t ) = c1e −5t + c2 e 2t
dy
= 6x − 7 y
dt
Hence,
1 −5t 3 2t
x (t ) = c1e + c2 e
3 2
Solve the following two IVPs by applying the eigenvalue and eigenvector method.
dy1
= y1 + 2 y2 , y1 ( 0 ) = 0
dt
dy2
= 3 y1 + 2 y2 , y2 ( 0 ) = −4
dt
Solution
1− λ 2
det ( A − λ I ) =
3 2 − λ
= λ 2 − 3λ − 4
= ( λ + 1) ( λ − 4 ) → λ1 = −1, λ2 = 4
λ1 = −1
1 2 x11 0
=
3
3 x12 0
−1
X=
1
λ2 = 4
−3 2 x 21 0
=
3 −2 x 22 0
2
−3 x 21 + 2 x 22 = 0 → x 21 = x 22
3
168 Numerical Methods in Chemical Engineering Using Python® and Simulink®
assuming, x 22 = 1, x 21 = 2 / 3
2/3
The eigenvector in this case is x =
1
The general solution is
−1 2
X ( t ) = c1e −t + c2 e 4 t
1
3
0 −1 2
−4 = c1 (1) 1 + c2 (1) 3
0 = −c1 + 2c2
−4 = c1 + 3c2
Rearranging,
8 4
c1 = − , c2 = −
5 5
8 −1 4 4 t 2
X ( t ) = − e −t − e
5 1 5 3
8 −t 8 4t
y1 = e − e
5 5
8 12
y2 = − e − t − e 4 t
5 5
Simulink Solution
The Simulink integrator, dragged from the Simulink/Commonly used Blocks library,
can be used to solve the two ODEs simultaneously, as shown in Figure 5.13.
Figure 5.14 is the plot generated by double-clicking on the Scope block of
Figure 5.13. The generated figure is the solution of the two equations ( y1 and y2 )
versus time (t).
An alternative Simulink solution uses the MATLAB function associated with the
MATLAB function.
Figure 5.15 is the Simulink block diagram using the eigenvalue and eigenvector
to solve Example 5.6.
Initial Value Problem Differential Equations 169
FIGURE 5.13 Solution of the equations in Example 5.6 using the Simulink integrator.
FIGURE 5.14 Plot generated by double-clicking the scope of Figure 5.13, generating the
solution of y1 and y2 versus time.
FIGURE 5.15 Simulink MATLAB function and the eigenvalue and eigenvector technique
to solve the two ODEs defined in Example 5.6.
170 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 5.16 Simulink generated plot signifies the solution of the two ODEs in Example
5.6 using eigenvalue and eigenvector.
% Example 5.6
function [Res1,Res2] = fcn(n)
% The coefficients of the Matrix
A = [1 2;
3 2];
% Calculating the eigenvalue and eigenvectors
[V, D] = eig(A);
% initial conditions
Y0 = [0; -4];
% Calculating the constants C1 and C2
c = diag(V\Y0);
t = linspace(0,n);
T = [t;t];
y = V*c*exp(D*T);
plot(t, y)
xlabel(“Time”)
ylabel(“y “, rotation =0 )
grid on;
str1 = ‘\leftarrow y_1’;
str2 = ‘y_2 \rightarrow’;
text (0.7,-20,str1,’FontSize’, 15);
text (0.55,-40,str2,’FontSize’, 15);
Res1 = y(1,end);
Res2 = y(2,end);
Initial Value Problem Differential Equations 171
FIGURE 5.17 Plot of the y1 and y2 versus time (t) generated by the Python program uses the
eigenvalue and eigenvector for solving the two equations defined in Example 5.6.
Python Solution
The following Python code utilizes the eigenvalue and eigenvector approaches to
solve the two equations described in Example 5.6. Running the Python program
generates the plot shown in Figure 5.17.
# Example 5.6
import numpy as np
import matplotlib.pyplot as plt
A = np.array([[1,2], [3,2]])
# extract eigenvalues
[w, v]= np.linalg.eig(A)
y10 = 0
y20 = -4
Pinitial = np.array([y10, y20])
C1, C2 = np.linalg.solve(v, Pinitial)
# combine everything to get the solution to P1
#t = np.linspace(0,2)
fig = plt.figure()
t=np.linspace(0,1,100)
y1 = C1 * np.exp(w[0]*t)*v[0,0] + C2 * np.exp(w[1] * t) * v[0,1]
y2 = C1 * np.exp(w[0]*t)*v[1,0] + C2 * np.exp(w[1] * t) * v[1,1]
#plt.plot(t, y1, t, y2)
plt.plot(t, y1, ‘-b’, label=’y1’)
plt.plot(t, y2, ‘:r’, label=’y2’)
plt.grid(True)
plt.ylabel(“y “, rotation = 0)
plt.xlabel(“Time”)
plt.legend()
172 Numerical Methods in Chemical Engineering Using Python® and Simulink®
5.4 SUMMARY
The aim of this chapter is to acquaint the reader with the numerical method required
in solving initial value ODEs that arise in chemical engineering topics such as fluid
flow, diffusion, reaction, mass, and heat transfer. IVP is an ODE with an initial con-
dition that determines the value of the unknown function at a given point in the
domain. In this chapter, we solved systems of two linear differential equations in
which the eigenvalues are real numbers. The eigenvalue is a number, and the eigen-
vector is a vector, both of which are hiding in the matrix.
5.5 PROBLEMS
1. Solve the following two ODE using eigenvalue and eigenvector techniques.
dy
= 3x + y, y ( 0 ) = −1
dt
dx
= 5x − y, x ( 0 ) = 2
dt
Answer:
3 7
x ( t ) = − e 2t + e 4 t
2 2
9 7
y ( t ) = − e 2t + e 4 t
2 2
dx
= − ( y + 5 x ) , x (1) = 0
dt
dy
= 4x − y, y (1) = 1
dt
Answer:
Answer:
133
x ( t ) = 3cos (8t ) e 2t + sin (8t ) e 2t
8
25
y ( t ) = −10 cos (8t ) e 2t + sin (8t ) e 2t
8
6. Solve the following two ODEs using the eigenvalue and eigenvector
technique.
dx
= 2x + 3y
dt
dy
= 4x + y
dt
Answer:
dy
= 3x
dt
dx
=y
dt
Answer:
x ( t ) = c1e 3t
+ c2 e − 3t
x ( t ) = 3c1e 3t
− 3c2 e − 3t
Initial Value Problem Differential Equations 175
REFERENCE
1. Griffiths, D.F. and Higham, D.J., 2011. Numerical Methods for Ordinary Differential
Equations. New York, NY: Springer.
6 Numerical Integration
of Definite Functions
Numerical integration estimates the values of definite integrals when a closed integral
form is challenging to find. The integral is evaluated at a finite set of points called
the points of integration, and a weighted sum of these values is used to approximate
the integral. This chapter aims to calculate definite integrals using various numerical
integration methods and validate the manual calculations with those programmed
using Python and the Simulink graphical programming of MATLAB. The integra-
tion methods include Simpson, Trapezoidal, Midpoint, Boole, and Romberg rules.
LEARNING OBJECTIVES
1. Calculate a definite integral using Simpson’s rule.
2. Estimate a definite integral using Trapezoidal rule.
3. Assess a definite integral using Midpoint rule.
4. Evaluate a definite integral using Boole’s rule.
5. Use Romberg’s rule to estimate the value of a definite integral.
6. Apply Simulink and Python to compute definite integrals.
6.1 INTRODUCTION
There are cases where it is difficult to find an analytical solution to a definite inte-
gral. However, it is possible to approximate the integral by dividing the function
into small subintervals and approximating the area. Numerical integration includes
a wide range of algorithms for calculating the numerical value of a definite integral.
Integration is often used to find the area under the graph of a function, and the area
can be found by adding small slices close to zero width. The definite integral is a for-
mal computation of the area under a function using tiny fragments or lines from the
area. A definite integral has start and end values: in other words, there is an interval
[a, b], where a and b are called limits, bounds, or boundaries.
Numerical integration methods combine evaluations of the integral to obtain an
approximation of the definite integral. Integration is evaluated at a finite set of points
called integration points, and a weighted sum of these values is used to approximate
the integral. In numerical analysis, numerical integration constitutes a wide range
of algorithms for calculating the numerical value of a definite integral, and thus,
the term is sometimes also used to describe the numerical solution of differential
equations. The fundamental problem that is considered by numerical integration is
calculating an approximate solution to a definite integral. They differ from analytic
integration in two ways: The first is approximate and will not yield an exact answer;
error analysis is an essential aspect of numerical integration. Second, it does not
result in an initial function from which the area can be determined due to arbitrary
bounds; it only produces an approximate numerical value for the area [1]. A definite
integral is an area under a curve between two fixed limits. The following is a definite
integral of f ( x ) concerning dx from a to b:
b
∫ f ( x ) dx
a
(6.1)
where a and b are lower and upper integral limits, f ( x ) is the integrand, and dx is the
integrating agent. The definite integral of the real-valued function:
b
∫ f ( x ) dx = F ( b) − F ( a)
a
(6.2)
When having a continuous function f ( x ) of the interval [a, b], the interval is divided
into n subdivisions of equal width (h), and from each interval, choose a point, xi .
Then the definite integral of the mentioned function is
b n
∫ f ( x ) dx = lim
n→∞ ∑ f ( x ) ∆x
i=1
i (6.3)
a
The number at the bottom of the integral sign (a) is the integral lower limit, and
(b) at the top of the integral sign is the integral upper limit. Numerical integration
estimates the values of definite integrals when an approximate value only of the defi-
nite integral is needed or when a closed-form integral is difficult to find. The most
used numerical integration techniques are the Simpson, Trapezoidal, and Midpoint
rules. Simpson’s rule approximates the definite integral using quadratic functions;
the Trapezoidal rule approximates the definite integral using trapezoidal regions; the
Midpoint rule approximates the definite integral using rectangular approximation;
Boole’s rule represents the area under the curve y = f ( x ) and between the coordi-
nates x = a and x = b. Romberg’s method evaluates the integrand at equally spaced
points, and the integrand must have continuous derivatives. The Romberg integration
(I) is approximated using the composite Trapezoidal rule.
b
h
∫ f ( x ) dx = 3 { f ( x ) + 4 f ( x ) + 2 f ( x ) + 4 f ( x ) + …+ f ( x )}
a
o 1 2 3 n (6.4)
To obtain an approximate value of the definite integral, split the main interval into
subintervals with an even number of n subintervals (Figure 6.1). Each step size
(width), h, can be defined as follows:
b−a
h= (6.5)
n
Simpson’s rule works best when the function has a similar shape to the approxima-
tion device within a narrow interval.
Use Simpson’s rule to integrate the following definite integral, dividing it into two
subintervals.
1
∫x dx
0
3
Evaluate the definite integral manually and confirm the manual calculations with
the following approaches:
Solution
Divide the main interval [0,1] into two subintervals with a width, h,
1− 0 1
h= =
2 2
h 1
Sn = f ( 0 ) + 4 f + f (1)
3 2
1
1
2
Sn = 0 + 4 + 1
3 8
1
Sn = = 0.25
4
1
x4 1 1
∫x dx = 4 = 4 − 0 = 4 = 0.25
0
3
The approximate numerical value agreed with the exact value of the definite
integral.
Simulink Solution
Using the Simpson rule, the Simulink block diagram for solving Example 6.1 is
described in Figure 6.2. The figure is followed by the MATLAB program associated
with the Simulink MATLAB function. The MATLAB function is connected to three
input ports: the lower integral limit (a), the upper integral limit (b), and the number
of subintervals (n). There is one output port connected to the Display block to release
the output value of the integral. The following program is the MATLAB code associ-
ated with the Simulink MATLAB function [2].
FIGURE 6.2 A Simulink solution using the Simpson rule of the definite integral defined in
Example 6.1.
s2=s2+f(x);
else
s1=s1+f(x);
end
end
res=(h/3)*(s0+2*s2+4*s1);
end
Python Solution
This Python program uses Simpson’s 1/3 rule to determine the approximate solu-
tion of the definite integral required in Example 6.1. In the implementation, the
function input parameters a, b, and n return the approximation results into the
Display block [3].
# Example 6.1
# Solution of a definite integral using Simpson’s rule with n
# subdivisions
def f(x):
return x**3
# the lower limit, upper limit, subinterval number
a=0
b=1
n=2
h= (b-a)/n
sum = f(a)+f(b)
d=4
for k in range(1,n):
x= a+k*h
sum= sum+ d*f(x)
d= 6-d
sum= h/3*sum
print(“value of the integral= “, sum)
Estimate the following definite integral using Simpson’s rule, dividing it into six
subdivisions.
4
1
∫ 2 x dx
1
2
Evaluate the definite integral manually and confirm the manual calculations with
the following approaches:
Solution
4 −1 1
h= =
6 2
h
Sn =
3
( f ( x0 ) + 4 f ( x1 ) + 2 f ( x2 ) + 4 f ( x3 ) + 2 f ( x4 ) + 4 f ( x5 ) + f ( x6 ))
As a function of x,
h 3 5 7
Sn = f (1) + 4 f + 2 f ( 2 ) + 4 f + 2 f ( 3) + 4 f + f ( 4 )
3 2 2 2
1
Sn =
2
3
( 0.5 + 4 (1.125) + 2 ( 2.0 ) + 4 (3.125) + 2 ( 4.5) + 4 (6.125) + 8) = 10.5
The correct solution is
4
1 x3 4 3 − 13
∫ 2 x dx = (2)(3) =
1
2
6
= 10.5
The approximate numerical value of the definite integral is identical to the exact
value.
Numerical Integration of Definite Functions 183
Simulink Solution
Figure 6.3 is the Simulink graphical programming using Simpson’s rule, represent-
ing the solution of the definite integral defined in Example 6.2. The figure is fol-
lowed by the MATLAB code associated with the MATLAB function, where a and b
are the lower and upper interval limits, respectively, and n is the number of subdi-
visions. The output port is connected to the Display block and outputs the integra-
tion value between the two limits (a and b).
The following program is the MATLAB code using Simpson’s rule and implanted
in the Simulink MATLAB function.
Python Solution
FIGURE 6.3 A Simulink block diagram using the Simpson rule demonstrating the solution
of the definite integral specified in Example 6.2.
184 Numerical Methods in Chemical Engineering Using Python® and Simulink®
# Example 6.2
# Simpson’s rule is available in Scipy.
import numpy as np
import scipy.integrate as spi
a=1
b=4
N=6
x=np.linspace(a, b, N-1)
y=0.5*x*x
approx=spi.simps(y, x)
print(“value of the integral= “, approx)
∫
f ( x ) = x 0.5dx
0
Evaluate the definite integral manually and check the manual calculations with the
following approaches:
Solution
b−a 8−0
h= = =2
n 4
Calculate the function values at the points of xi : [0, 2, 4, 6, 8]
f ( x o ) = f ( 0 ) = 0 0.5 = 0
f ( x1 ) = f ( 2 ) = 20.5 = 1.414
f ( x 2 ) = f ( 4 ) = 4 0.5 = 2
f ( x3 ) = f ( 6 ) = 60.5 = 2.449
f ( x 4 ) = f (8 ) = 80.5 = 2.828
Numerical Integration of Definite Functions 185
The percent error in approximating the integral compared with the exact analytical
solution
15.09 − 14.86
E= × 100% = 1.5%
15.09
Simulink Solution
Figure 6.4 represents Simpson’s rule programmed in MATLAB and linked to the
Simulink MATLAB function. The Simulink block diagram can be used to solve
other functions by changing the values of integral limits (a, b) and the number
of subintervals (n). Other functions can replace the desired integral function in
the MATLAB code to solve other definite integrals. The following program is the
MATLAB code utilizing the Simpson rule and embedded in the Simulink MATLAB
function located at the center of Figure 6.4.
FIGURE 6.4 Simulink solution employing Simpson’s rule for solving the definite integral
associated with Example 6.3.
Python Solution
In this example, the Simpson rule function is included, and there is no need to
import the “SciPy. integrate” library. The Simpson function keeps track of the run-
ning sum and the multiplicands associated with each evaluation of the function,
but the function to be evaluated is an actual Python program that takes in a single
argument, x, and returns its value. The Trapezoidal rule yields comparable results,
and the following is the Python program written to evaluate the desired definite
integral using Simpson’s rule with n subdivisions.
# Example 6.3
# The program evaluates a definite integral using Simpson’s
# rule with n subdivisions
# Implementing Simpson’s 1/3 rule
def f(x):
return x**0.5 # The desired function
def simpson(x0,xn, n):
h= (xn-x0)/n # The step size
Sum=f(x0)+f(xn)
for i in range(1,n):
j = x0 + i*h
if i%2 == 0:
Sum = Sum + 2 * f(j)
else:
Sum= Sum + 4 * f(j)
#Finding value
Sum = Sum * h/3
return Sum
result = simpson(0,8, 4)
print(“The value is: %0.5f” % (result))
The execution result is
The value is: 14.85549
Numerical Integration of Definite Functions 187
b−a
h=
n
Such that,
The Trapezoidal rule approximates the definite integrals and uses the linear approxi-
mation of the functions. When the underlying function is smooth, the Trapezoidal
rule does not give values as accurate as Simpson’s rule because Simpson’s rule
uses the quadratic approximation rather than the linear approximation used by the
Trapezoidal rule. Both the Trapezoidal rule and Simpson’s rule give the approxima-
tion value. By contrast, Simpson’s rule gives more accurate values of the definite
integral.
The function, f ( x ), is a continuous function over the interval [a, b]. The approxi-
mate solution of such a function is given by
b
h
∫ f ( x ) dx = 2 ( f ( x ) + 2 f ( x ) + 2 f ( x ) + …+ 2 f ( x
a
0 1 2 n −1 ) + f ( xn )) (6.5)
Estimate the following definite integral using the Trapezoidal rule utilizing four
subintervals, estimating the absolute and relative error.
1
∫x dx
0
2
Evaluate the definite integral manually and support the manual calculations with
the following approaches:
Solution
First, calculate the step size, h, using the integral upper limit (b) and lower limit (a)
and the number of the subintervals (n):
b − a 1− 0 1
h= = =
n 4 4
1
1
1 1 3
∫
4
Tn = x dx =2
f ( 0 ) + 2 f + 2 f +…+ 2 f + f (1)
2 4 2 4
0
Find the functions at different intervals and substitute them into the Trapezoidal
technique formula
1
1
11
1 1 9
∫
4
Tn = x dx = 0 + 2 16 + 2 4 +…+ 2 16 + (1) = 32 = 0.344
2
2
0
1 11 1
− =
3 32 192
1 11 1
−
3 32 192
= × 100% = 3.1%
1 1
3 3
Simulink Solution
Using the MATLAB function that utilizes the Trapezoidal rule implanted in the
Simulink MATLAB function (Figure 6.6), the embedded MATLAB code follows
Figure 6.6. The Simulink block diagram can be used to solve other functions by
changing the values of integral limits (a, b), the number of subintervals (n), and the
desired function in MATLAB code.
The following program is the MATLAB code embedded in the Simulink
MATLAB function and centered in Figure 6.6. The function can be used to solve
other definite integrals by changing the desired function.
FIGURE 6.6 Trapezoidal rule programmed in Simulink/MATLAB function for solving the
definite integral specified in Example 6.4.
190 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Python Solution
The Trapezoidal algorithm is used without importing the function from the Python
library in the solution of this example using Python programming. The function (f)
can be changed to any other desired function. The Trapezoidal rule yields compa-
rable results to Simpson’s rule.
# Example 6.4
# Python program to evaluate a definite integral using
Trapezoidal’s # rule with n subdivisions
# Implementing Trapezoidal’s rule
def trapezoid(a, b, n):
f= lambda x: x**2 # the desired function
sum = 0
h= (b - a ) / n
for k in range(n + 1):
x = a + (k * h)
summand = f(x)
if (k != 0) and (k != n):
summand *= 2
sum += summand
return sum * h / 2
# Example of use
result =trapezoid(0, 1, 4)
print(“The calculated value is: %0.5f” % (result))
Mn = h ∑ f (m )
i=1
i (6.6)
The Midpoint rule is more accurate than the Trapezoidal rule. Figure 6.7 graphically
demonstrates the Midpoint rule.
Use the Midpoint rule with four subdivisions to evaluate the following definite
integral.
Numerical Integration of Definite Functions 191
∫x dx
0
2
Compare the approximate numerical integration result using the Midpoint rule
with actual analytical integration value and Python and Simulink/MATLAB pro-
gramming of the Midpoint rule.
Solution
b − a 1− 0 1
h= = =
n 4 4
0 − − 1 − − 1 − − 3 − −1
4 2 4
The middle point of these subintervals
0 − 1 − 1 − 3 − 1 − 5 − 3 − 7 − 1
8 4 8 2 8 4 8
192 Numerical Methods in Chemical Engineering Using Python® and Simulink®
∫x dx = 4 { 64 + 64 + 64 + 64 } = 64 = 0.328
1
2 1 1 9 25 21 21
A− B
1 21 1
− =
3 64 192
The relative error is the error as a percentage of the actual value and is given by
A− B
× 100%
A
where A is the actual value and B is our estimated value. Figure 6.8 shows the
Simulink block diagram representing the Midpoint rule function. The Simulink
block diagram can be utilized to solve other functions by changing the values of
integral limits (a, b), the number of subintervals (n), and the desired function in
MATLAB code.
The following MATLAB program of the Midpoint method is rooted in the
MATLAB function (Figure 6.8).
FIGURE 6.8 Simulink midpoint block diagram represents the solution of the definite inte-
gral required in Example 6.5.
Numerical Integration of Definite Functions 193
for i=1:n
sum = sum +h*(f((a+(a+h))/2));
a=a+h;
end
Result = sum;
End
Python Solution
The Midpoint rule evaluates the desired function between each point in the
required interval. Using the functions from the Python library is certainly much
faster to implement. By contrast, the following Midpoint method in Python was
interesting to learn how the function works.
# Example 6.5
# Python program to evaluate a definite integral using Midpoint’s
# rule with n subdivisions
# implementing Midpoint’s Rule
def midpoint(a, b, n):
f=lambda x:x**2 # The desired function
sum = 0
x_in=((2*n+1)*a-b)/(2*n)
h=(b-a)/n
for k in range (1,n+1):
x=x_in+(k*h)
sum= sum + f(x)
return sum*h
# Example to use
Res = midpoint (0,1,4)
print(“The calculated value is: %0.5f” % (Res))
The result after the program execution is
The calculated value is: 0.32812
Estimate for following definite integral using Boole’s rule, assuming the number of
intervals equals 4.
1
dx
∫ 1+ x
0
2
194 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Compare the result of the approximate numerical integration using Boole’s rule
with actual analytical integration value and employ Python and Simulink/MATLAB
programming of Boole’s rule.
Solution
b − a 1− 0 1
h= = =
4 4 4
The Simulink block diagram represents the solution of the definite function speci-
fied in Example 6.6, shown in Figure 6.10. Boole’s method programmed in the
MATLAB code is associated with the Simulink MATLAB function. The Simulink
block diagram can be utilized to solve other integrals by changing the values of
Numerical Integration of Definite Functions 195
FIGURE 6.10 Simulink block diagram utilizing Boole method to estimate the definite inte-
gral needed in Example 6.6.
integral limits (a, b), the number of subintervals (n), and the desired function in
MATLAB code.
The following is the MATLAB code implanted in the Simulink MATLAB func-
tion to solve the equation required in Example 6.6.
Python Solution
Here, Example 6.6 is solved by programming Boole’s rule in Python. The program
evaluates the required integral within the interval [0, 1] and with n subdivisions.
# Example 6.6
# Python program to evaluate a definite integral using Boole
method
# implementing the Boole method
def Boole(a, b, n):
f=lambda x:1/(1+x**2 )# The desired function
h = (b-a)/n
sum = 7*(f(a)+f(b))
sum = sum +32*(f(a+h)+f(b-h))
sum = sum+ 12*(f(a+2*h))
res = 2*sum*h/45
return res
# Example to use
res = Boole (0,1,4)
print(“The calculated value is: %0.5f” % (res))
∫ f ( x ) dx
a
∫
I = f ( x ) dx = f ( a ) + 2
2
i=1
∑
f ( xi ) + f ( b )
a
where
b−a
h=
n
xi = xi −1 + h
This procedure ends when two successive values are remarkably close (Figure 6.11).
TABLE 6.1
The Romberg Integration Table
hi I i′ I i′ I i′′ I i′′′
h I1 1
I1′ = I 2 + ( I 2 − I1 )
3
1
I1′′= I1′ + ( I 2′ − I1 )
3
h I2 1 1
I 2′ = I 3 + ( I3 − I2 ) I1′′′= I 2′′+ ( I 2′′− I1′′)
2 3 3
1
I 2′′ = I 3′ + ( I 3′ − I 2 )
3
h I3 1
I 3′ = I 4 + ( I4 − I3 )
4 3
h I4
8
Numerical Integration of Definite Functions 197
FIGURE 6.11 Graphical representation of the (a) Romberg integration and (b) Richardson
extrapolation.
∫x dx
0
2
Solution
b−a 8−0
h= = =2
n 4
f (x) = x2
h=4
8
h
∫x dx = 2 { f ( x ) + 2 f ( x ) + f ( x )}
0
2
o 1 4
∫
I 1 = x 2 dx =
4
2
{ f ( 0 ) + 2 ( f ( 4 )) + f ( x )}
4
0
∫
I1 = x 2dx =
4
2
{(0 ) + 2 (4 ) + (8 )} = 192
2 2 2
0
198 Numerical Methods in Chemical Engineering Using Python® and Simulink®
h=2
8
∫x dx = 2 { f ( x ) + 2 ( f ( x ) + f ( x ) + f ( x )) + f ( x )}
2 h
o 1 2 3 4
0
∫
I 2 = x 2dx =
h
2
{ f ( 0 ) + 2 ( f ( 2) + f ( 4 ) + f (6)) + f (8)}
0
∫
I 2 = x 2 dx =
2 2
2
{ ( )
0 + 2 22 + 4 2 + 62 + 82 ) = 176 }
0
h=1
I3 =
1 2
2
{ (
0 + 2 12 + 22 + 32 + 4 2 + 52 + 62 + 72 + 82 = 172 ) }
h = 0.5
I3 =
0.5 2
2
{ (
0 + 2 0.52 + 12 + 1.52 + .. + 7.52 + 82 = 171 ) }
The rest of the calculation is listed in Table 6.2.
Finally,
1 1
I1′′′= I 2 + ( I 2′′− I1′′) = 170.66 + (170.66 − 170.66) = 170.66
3 3
8
∫x dx = 170.66
0
2
Simulink Solution
The Romberg method programmed in the MATLAB code is associated with the
Simulink MATLAB function. The Simulink block diagram can be utilized to solve other
integrals by changing the values of integral limits (a,b), the number of subintervals
TABLE 6.2
This Arithmetic Procedure Ends When Two Consecutive Values Are
Very Close (170.66)
hi Ii I i′ I i′′
h 192 176 + 1/3 (176 – 192) = 170.66 170.66 + 1/3 (170.66 – 170.66) = 170.66
h 176 172 + 1/3 (172 – 176) = 170.66 170.66 + 1/3 (170.66 – 170.66) = 170.66
2
h 172 171 + 1/3 (171 – 172) = 170.66
4
h 171
8
Numerical Integration of Definite Functions 199
(n), and the desired function in MATLAB code. The Simulink block diagram for solv-
ing the definite integral required in Example 6.7 is shown in Figure 6.12. To reach
h = 0.5, the program’s n value equals 16.
The following is the MATLAB program refers to the Romberg integration
method associated with the Simulink MATLAB function.
FIGURE 6.12 Simulink solution applying Romberg’s rule programmed to solve the definite
integral identified in Example 6.7.
200 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Python Solution
# Example 6.7
# The program evaluates a definite integral using Romberg’s rule
# Implementing the Romberg method
import numpy as np
from scipy import integrate
f = lambda x: x**2 # The desired function
# using scipy.integrate.romberg()
res = integrate.romberg(f, 0, 8, show = True)
print(“The calculated value is: %0.5f” % (res))
The result of the definite integral of the function defined in Example 6.7 is as
follows:
h = 0.5
0.5
I1 = f ( x ) dx =
2
{ f ( 0 ) + 2 f ( 0.5) + f (1)}
0.5
I1 = f ( x ) dx =
2
{ f ( 0 ) + 2 f ( 0.5) + f (1)}
Numerical Integration of Definite Functions 201
0.5
h= = 0.25
2
I 2 = f ( x ) dx =
0.25
2
{ }
f ( 0 ) + 2 ( f ( 0.25) + f ( 0.5) + f ( 0.75)) + f (1)
0.25
I 2 = f ( x ) dx =
2
{1 + 2 ( 0.8 + 0.667 + 0.5714 ) + 0.5} = 0.697
0.25
h= = 0.125
2
0.125 f ( 0.125) + f ( 0.25) + f ( 0.375) + f ( 0.5) + f (0.625 + f ( 0.75)
I3 = f (0) + 2 + f (1)
2 + f (0.875
0.125
I3 =
2
{(1) + 2( 0.89 + 0.8 + 0.727 + 0.667 + 0.615 + 0.57 + 53) + 0.5} = 0.694
Table 6.3 lists the rest of the calculation.
The Simulink graphical programming utilizing the Romberg rule is demon-
strated in Figure 6.13, followed by the MATLAB code associated with the MATLAB
function.
By double-clicking the Simulink MATLAB function block, the following code
will appear.
TABLE 6.3
Romberg Integration Method of the Definite Integral Specified in Example
6.8
hi Ii I i′ I i′′
h 0.708 0.697 + 1/3 (0.697 – 0.708) = 0.6933 0.6931 + 1/3 (0.693 – 0.6933) = 0.6929
h 0.697 0.694 + 1/3 (0.694 – 0.697) = 0.693
2
h 0.694
4
202 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 6.13 Simulink program utilizing Romberg integration method for solving the defi-
nite integral identified in Example 6.8.
r(2,1)=(r(1,1) + h*rv)/2;
for j=2:i
l=2^(2*(j-1));
r(2,j)=r(2,j-1)+(r(2,j-1)-r(1,j-1))/(l-1);
end
for k=1:i
fprintf(‘%7.5f’, r(2,k));
end
fprintf(‘\n\n’);
h=h/2;
for j=1:i
r(1,j)=r(2,j);
end
end
Result=r(1,n);
end
Python Solution
In this example, the Romberg function is imported from the built-in Python library
“SciPy. integrate”. We used Romberg integration of a callable function from limit (a
to b) by using “SciPy. integrate”. Romberg’s rule is available in SciPy.
# Example 6.8
# The program evaluates the definite integral using Romberg’s
rule
# import scipy.integrate
from scipy import integrate
f = lambda x: 1/(1+x) # desired function
# using scipy.integrate.romberg()
res = integrate.romberg(f, 0, 1, show = True)
print(res)
Numerical Integration of Definite Functions 203
6.7 SUMMARY
Numerical integration evaluates a definite integral from a set of integrand f ( x )
numerical values. The most widely used methods of numerical integration are the
Midpoint rule, Trapezoidal rule, and Simpson’s rule. The Midpoint rule approximates
the definite integral using rectangular areas, while the Trapezoidal rule approximates
the definite integral using a trapezoidal approximation. We can use numerical inte-
gration to estimate the values of definite integrals when it is difficult to find a closed
form or when only an approximate value of the definite integral is needed. The most
widely used methods of numerical integration are the Midpoint rule, Trapezoidal
rule, and Simpson’s rule.
6.8 PROBLEM
1. Solve the integral by the Trapezoidal rule with h = 0.5, 25, and 0.125. Then
obtain a better estimate using the Romberg integration method. Compared
with Simulink and the analytical solution.
1
1
f (x) =
∫ 1 + x dx
0
10
∫x dx
2
3
Answer: 2496
204 Numerical Methods in Chemical Engineering Using Python® and Simulink®
2
1
f (x) =
∫ x dx
1
Answer: 0.694
4. Calculate the approximate value of the following definite integral using
Simpson’s rule with n = 6 (note that n should be an even number). Compared
with the Simulink and the analytical solution.
2 2
1
∫0
f ( x ) dx =
∫ ( x + 1)
0
0.5 dx
Answer: 1.4642
3.5 3.5
∫ f ( x ) dx = ∫ 0.25 x dx
−0.5 −0.5
3
Answer: 9
=
∫x ( 2 − x ) dx
1
Answer: −16.7407
0.6
∫ ( x + 1)
2 −1
dx
0.2
Answer: 0.343
Numerical Integration of Definite Functions 205
∫ ( x + 1)
2 −1
dx
0
Answer: 1.3624
∫ ( x + 1)
−1
dx
0
Answer: 0.6931
∫ ( x + 1)
2 −1
dx
0
Answer: 0.7853
REFERENCES
1. Davis, P.J. and Rabinowitz, P., 2014, Methods of Numerical Integration. Orlando, FL:
Academic Press Inc.
2. Woodford, C. and Phillips, C., 2012, Numerical Methods with Worked Examples.
Cham: Springer International Publishing,.
3. Kong, Q., Siauw, T. and Bayen, A., 2020, Python Programming and Numerical
Methods: A Guide for Engineers and Scientists. Amsterdam: Elsevier Science.
7 Numerical Solution of
Ordinary Differential
Equations
An ordinary differential equation (ODE) is a mathematical equation relating one
or more functions of the independent variable with their derivatives. Differential
equations are important to chemical engineers as they are essential tools for the
mathematical modeling of any problem involving rate changes. The chapter presents
Euler, Midpoint, Heun, Runge-Kutta, and Picard’s iteration methods to solve differ-
ent ODEs. The methods produce the integral value of the desired ODE in different
approaches and numerical precision.
LEARNING OBJECTIVES
1. Solve ODEs using the Euler method.
2. Utilize the Midpoint method to solve ODE.
3. Use Heun’s method to solve ODE.
4. ApplyRunge-Kutta fourth-order (RK4) method.
5. Apply Picard’s iterative method.
6. Employ Python and Simulink to solve ODE.
7.1 INTRODUCTION
Solving differential equations is an essential skill for mathematicians and engineers.
However, many differential equations cannot be solved using traditional symbolic calcu-
lations (analysis). Therefore, a more advanced solution method is required to solve more
complex or lengthy differential equations. Accordingly, a numerical approximation of
the solution is used as a method of solution and is often sufficient for practical purposes.
A differential equation is an equation that contains one or more functions and
their derivatives; it contains derivatives that are either ordinary derivatives or par-
tial derivatives. An ODE contains one or more functions of one independent vari-
able. Different numerical methods are used to solve the numerical approximation for
ODEs; depending on the desired value, the methods are used to find the numerical
approximations to the solution of ODEs. The integral solution for ODEs is desired
in several cases, and this use is known as ‘numerical integration’. The reason behind
numerical integration is that many differential equations cannot be solved using sym-
bolic computation as they require long computation and are complex equations. In
engineering and for practical purposes, an ODE is extracted from a practical applica-
tion, and the integral is required, so the numerical approximation to the solution is
sufficient to provide accurate results. Various algorithms studied in this chapter can
be used to compute the integral value for ODEs, each with a different approach and
accuracy level. A manual numerical solution solves each example in this class, and
the manual solution is confirmed using Simulink/MATLAB and Python. The objec-
tive of explaining different solution methods is to educate the reader on software
usage, keep up with the advancement of technology, and utilize available resources.
The Euler solution has two main methods, namely explicit and implicit, each pre-
sented in this chapter. Furthermore, other methods, such as Midpoint, Heun, Runge-
Kutta, and Picard’s iteration, are explained in the solution method.
dy
= f ( x , y ) , y ( x o ) = yo
dx
The Euler method solution is based on the following equation:
yi +1 = yi + hf ( xi , yi )
Solve the following initial value ODE using the explicit Euler method and step size,
h = 0.1, calculate the value of y at x = 1.4.
dy
= 3x 2 y
dx
y ( x o ) = yo → y (1) = 2
Compare the approximate results obtained from the Euler method, Simulink, and
Python to the actual analytical solution values
y( x ) = 2 * ex
2
−1
Solution
dy
In the Euler equation, the f ( xi , yi ) is the derivative equation , and is substituted
dx
as such. Knowing the initial condition, at x o = 1, y (1) = 2, we start by adding the
step size to the initial value of x, x = x + h. At each step, the values of x and y are
taken from the previous step solved, and this is why an initial value is required for
this method to work.
x1 = 1.1
y1 = yo + hf ( x o , yo )
y1 = 2 + 0.1 f (1, 2 )
x 2 = 1.2
y2 = y1 + hf ( x1 , y1 )
x3 = 1.3
y3 = y2 + hf ( x 2 , y2 )
x 4 = 1.4
y4 = y3 + hf ( x3 , y3 )
FIGURE 7.2 Solver setup of a Simulink integral to use the forward Euler method in the
solution case in Example 7.1.
Numerical Solution of ODEs 211
FIGURE 7.3 Simulink block diagram using the Euler method of the equation defined in
Example 7.1.
FIGURE 7.4 Simulink block diagram using the Euler method of equation specified in
Example 7.1, the stop time is four.
The following MATLAB code represents forward Euler’s method that combines
the Simulink MATLAB function to solve the following initial value problem (IVP)
defined in Example 7.1.
for i=1:n+1
k1 = f(x(i), y(i));
y(i+1) =y(i) + h*(k1);
end
Res=y(i+1);
End
Python Solution
The Python program is utilized to solve the IVP stated in Example 7.1. The approxi-
mate numerical integration value and the exact analytical solution are illustrated
in Figure 7.5. The figure shows the approximate solution using the forward Euler
method and the exact analytical solution. Figure 7.5 shows an increasing gap as the
x value is increased due to an accumulated error. The discrepancy gap between
the approximated and the exact solution can be shrunk by decreasing the step size,
as decreasing the step size will increase the accuracy of the solution. The Spyder
editor version five is used to edit and run the following Python code.
FIGURE 7.5 Comparison of the Euler’s method programmed in Python and the accurate
analytical solution of the ODE defined in Example 7.1.
Numerical Solution of ODEs 213
for i in range(1,n):
y[i] = y[i-1] + h*f(x[i-1], y[i-1])
print(“x_n\t y_n”)
for i in range(n):
print(x[i], “\t”, format(y[i], ‘6f’))
# plot section
x_true = np.linspace(1,1.4,10)
y_true = 2*np.exp(x_true**2-1)
plt.plot(x, y, ‘o-’, x_true, y_true, ‘r’)
plt.axis([1,1.45,2,8])
plt.legend([‘Euler’, ‘True’])
plt.xlabel(“x”)
plt.ylabel(“y”)
plt.grid(True)
plt.title(“Euler Solution of $y’=3x^2y, y(1)=2$”)
plt.show()
The forward Euler (explicit) method is a first-order numerical procedure for solv-
ing ODEs with a given initial value. Consider the following first-order differential
equation with an initial condition y ( 0 ) = 1, and a step size, h = 0.025, find y(0.1).
dy
= x + y + xy
dx
Manual Solution
f ( x , y ) = x + y + xy
x o = 0, yo = 1, h = 0.025
yi = yi −1 + hf ( xi −1 , yi −1 )
y1 = yo + hf ( x o , yo ) = 1 + 0.025 f ( 0,1)
y1 = 1 + 0.025 × ( 0 + 1 + 0 × 1) = 1.025
Accordingly,
y ( 0.025) = 1.025
214 Numerical Methods in Chemical Engineering Using Python® and Simulink®
TABLE 7.1
Explicit Euler Method
i x y
0 0 1
1 0.025 1.025
2 0.05 1.051891
3 0.075 1.080753
4 0.1 1.111673
FIGURE 7.6 Setting the solver to the Euler forward method of Example 7.2.
Numerical Solution of ODEs 215
FIGURE 7.7 Simulink solution using fixed-point iteration Euler method of Example 7.2.
FIGURE 7.8 Simulink MATLAB function using the Euler method of the ODE defined in
Example 7.2.
f=@(x, y).
function Res = euler(a, b, h, y0)
f = @(x, y)(x+y+x*y);% ODE
x = a:h:b;
n = (b-a)/h;
y=zeros(size(x));
y(1)=y0;
216 Numerical Methods in Chemical Engineering Using Python® and Simulink®
for i=1:n
y(i+1) =y(i) + h*f(x(i), y(i));
end
Res=y(i+1);
end
Python Solution
FIGURE 7.9 Python numerical approximate solution of the ODE specified in Example 7.2.
Numerical Solution of ODEs 217
plt.xlabel(“x”)
plt.ylabel(“y”)
plt.grid(True)
plt.axis([0,0.12,1,1.12])
plt.title(“Euler Approximation Solution”)
plt.grid(True)
plt.show()
The results
x_n y_n
0.000000 1.000000
0.025000 1.025000
0.050000 1.051891
0.075000 1.080753
0.100000 1.111673
dy
= f ( x, y) , y ( x o ) = yo
dx
The backward Euler (Implicit) method is
yi +1 = yi + hf ( xi +1 , yi +1 )
The new approximation yi+1 appears on both sides of the equation, and thus the
method needs to solve an algebraic equation for unknown yi+1. Figure 7.10 shows the
presentation of the backward Euler method.
The backward Euler method is a first-order numerical procedure for solving ODEs
with a given initial value. Consider the following first-order differential equation
with an initial condition y ( 0 ) = 1, and a step size, h = 0.025, find y(0.1).
dy
= x + y + xy
dx
Manual Solution
yi = yi −1 + hf ( xi , yi )
f ( x , y ) = x + y + xy
Substituting,
i = 1, x = 0.025
y1 = yo + hf ( x1 , y1 ) = yo + h ( x1 + y1 + x1 y1 )
i = 2, x = 0.05
y2 = y1 + hf ( x 2 , y2 ) = y1 + h ( x 2 + y2 + x 2 y2 )
i = 3, x = 0.075
y3 = y2 + hf ( x3 , y3 ) = y2 + h ( x3 + y3 + x3 y3 )
i = 4, x = 0.1
y4 = y3 + hf ( x 4 , y4 ) = y3 + h ( x 4 + y4 + x 4 y4 )
Rearranging,
( h + x1h − 1) y1 + 0 + 0 + 0 = −hx1 − yo
y1 + ( h + x3h − 1) y2 + 0 + 0 = − hx 2
0 + y2 + ( h + x3h − 1) y3 + 0 = − hx3
0 + 0 + y3 + ( h + x 4 h − 1) y4 = − hx 4
Numerical Solution of ODEs 219
The below Python program solves the above set of linear algebraic equations. The
result for x1 to x 4 are shown below the Python program.
The answer is shown in a 1 × 4 matrix, each column representing a step in the solu-
tion, and the last column is at x = 0.1.
FIGURE 7.11 Simulink modeling configuration menu for setting the simulation time, solver
selection, and solver details of the backward Euler method for solving the equation defined
in Example 7.3.
FIGURE 7.12 Backward Euler method solution of the equation specified in Example 7.3.
% Initialize arrays...
% The first elements take xinit
% yinit correspondingly, the rest fill with 0s.
x = [xinit zeros(1,n)];
y = [yinit zeros(1,n)];
%Numeric routine
for i = 1:n
x(i+1) = x(i)+h;
ynew = y(i)+h*(f(x(i), y(i)));
y(i+1) = y(i)+h*f(x(i+1), ynew);
end
Res = y(i+1);
End
Numerical Solution of ODEs 221
FIGURE 7.13 Simulink block diagram using the backward Euler (implicit) method for solv-
ing the equation required in Example 7.3.
Python Solution
The Python program below uses the backward Euler method to solve the equa-
tion given in Example 7.3. Running the Python program produces the following
numerical approximation results containing the values of y at different values of x
with a step size of h (0.025).
tp = x[i] + h
yp = yo + h * f ( to, yo )
yp = fsolve (backward_euler_residual, yp, args = (f, to, yo,
tp))
x[i+1] = tp
y[i+1] = yp
print (“%.3f”%x[i], “%.3f”%y[i])
return x, y
def backward_euler_residual ( yp, f, to, yo, tp ):
value = yp - yo - ( tp - to ) * f ( tp, yp );
return value
backward_euler ( f, tspan, y0, n )
The results obtained from running the Python code are shown below:
Solution
x y
--- -----
0.000 1.000
0.025 1.027
0.050 1.056
0.075 1.087
0.100 1.120
dy
= f ( x , y ) , y ( 0 ) = yo
dx
Using the Midpoint numerical method,
yi +1 = yi + k2 h
here k1
k1 = f ( xi , yi )
Numerical Solution of ODEs 223
and k2
k2 = f x + , yi + k1
h h
2 2
dy
= 3e − x − 0.4 y, y ( 0 ) = 5
dx
Confirm the manual calculations with Python and Simulink/MATLAB programming.
Solution
k1 = f ( xi , yi ) = f ( 0, 5) = 3 * e 0 − 0.4 ( 5) = 1
Calculate
h h 1.5 1.5
k 2 = f x + , yi + k1 = f 0 +
, 5+ (1)
2 2 2 2
At x 2 = 3, the value of k1
h 1.5 1.5
( −0.8)
h
k 2 = f x + , yi + k1 = f 1.5 + , 3.676 +
2 2 2 2
For this example, a Simulink diagram is created, and the MATLAB function is dragged
from the Simulink library to the work environment to solve the IVP described
in Example 7.4. Figure 7.15 shows the Simulink block diagram centered by the
MATLAB function and connected between four input ports and one output Display.
FIGURE 7.15 Simulink solution using MATLAB function and the Midpoint method of the
ODE defined in Example 7.4.
Numerical Solution of ODEs 225
The four input ports are the lower limit interval (a), the upper limit interval (b), the
step size (h), and the initial value of y( y0 ) . The Display icon yields the value of the y
at the upper limit interval or the simulation stop time (i.e., 3). The figure is followed
with embedded MATLAB functions. The following MATLAB codes programmed
the Midpoint method combined with the Simulink MATLAB function for solving
the ODE described in Example 7.4.
Python Solution
The following Python code solves the ODE specified in Example 7.4 using the
midpoint method. Unless the right-hand side of the ODE is linear in the dependent
variable, each of the midpoint steps requires solving an implicit nonlinear equa-
tion. Using the midpoint formula, the user can calculate the curve representing the
solution to the normal differentiation of an equation with an initial value.
The results obtained from running Python code with midpoint in solving the given
equation in Example 7.4 are shown as follows:
226 Numerical Methods in Chemical Engineering Using Python® and Simulink®
--------SOLUTION--------
at x = 1.5 , yn = 3.6756494873345655
at x = 3.0 , yn = 2.304947496982057
dy
= f ( x , y ) , y ( 0 ) = yo
dx
Heun’s method involves the determination of two derivatives for the interval at the
initial point and the endpoint.
k1 = f ( xi , yi )
k2 = f ( x + h, yi + k1h )
k + k2
yi +1 = yi + h 1
2
Solve the following initial value nonlinear ODE using Heun’s method to find y at
x = 5 using a step size, h = 0.5
dy 100 + y
= , y ( 0.5) = 20
dx 5x
Solution
100 + y
f ( x, y) =
5x
At
100 + 20
k1 = f ( x 0 , yo ) = f ( 0.5, 20 ) = = 48
5 ( 0.5)
100 + 44
k 2 = f ( x o + h, yo + k1h ) = f ( 0.5 + 0.5, 20 + 48 * 0.5) = f (1, 44 ) = = 28.8
0.5 (1)
The calculated y1
k +k 48 + 28.8
y1 = y0 + h 1 2 = 20 + 0.5 = 39.2
2 2
dy 100 + y
=
dx 5x
y x
dy 1 dx
∫
yo
=
100 + y 5 ∫x
xo
Integrate
100 + y 1 x
ln = ln
100 + yo 5 x o
228 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Simplify
1 1
1 5 5
1 1
x 5
y = (100 + yo ) − 100 = 120 x − 100 = 137.844 x 5 − 100
xo 0.5
1
y = 137.844 x 5 − 100
Table 7.2 lists the approximate numerical solution using Heun’s method and the
exact analytical solution of the ODE specified in Example 7.5.
Simulink and MATLAB Solution
TABLE 7.2
Heun’s Method of Numerical Approximation and the Exact Analytical
Solution of the Equation Defined in Example 7.5
x k1 k2 yHeun yexact
0.5 20.000 20.000
1 48.000 28.800 39.200 37.844
1.5 27.840 20.416 51.264 49.488
2 20.169 16.135 60.340 58.341
2.5 16.034 13.469 67.715 65.568
3 13.417 11.628 73.977 71.717
3.5 11.598 10.273 79.445 77.093
4 10.254 9.229 84.315 81.886
4.5 9.216 8.397 88.718 86.222
5 8.387 7.716 92.744 90.187
Numerical Solution of ODEs 229
FIGURE 7.17 Simulink configuration parameters utilizing the Heun method to solve the
ODE specified in Example 7.5.
FIGURE 7.18 Simulink block diagram using fixed-step size Heun’s method for the equa-
tion solution specified in Example 7.5, the stop time equals five.
xi=x0;
for i =1:n
k1= f(xi, yi);
k2= f(xi+h, yi+(h*k1));
yf =yi+(h/2)*(k1+k2);
yi=yf;
xi = xi +h;
end
Res=yi;
End
230 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 7.19 Simulink block diagram using the Heun method to solve the equation defined
in Example 7.5, stop time equals five.
Python Solution
The following is the Python code created to calculate the curve representing the
Heun method of the first-order ODE defined in Example 7.5.
The results obtained after running the Python program that solves the ODE speci-
fied in Example 7.5 are as follows:
--------SOLUTION--------
at x= 0.5 yn = 20
at x= 1.0 yn = 39.2
at x= 1.5 yn = 51.264
at x= 2.0 yn = 60.33984
Numerical Solution of ODEs 231
at x= 2.5 yn = 67.71547264
at x= 3.0 yn = 73.97685028522667
at x= 3.5 yn = 79.4446941513338
at x= 4.0 yn = 84.31533584972715
at x= 4.5 yn = 88.71842442835953
at x= 5.0 yn = 92.7444174828312
k1 = f ( xi , yi )
k2 = f xi + , yi + k1
h h
2 2
h h
k3 = f xi + , yi + k2
2 2
k4 = f ( xi + h, yi + hk3 )
h
yi +1 = yi + ( k1 + 2k2 + 2k3 + k4 )
6
Solve the following initial value ODE using the RK4 method to find the value of y
at x = 1.5. Use a step size of 0.1(h = 0.1).
dy
= 3x 2 y, x (1) = 2
dx
Solution
k1 = f ( x 0 , y0 ) = f (1, 2 ) = 3 (1) 2 = 6
2
h h 0.1 0.1
6 = 3 (1.05) ( 2.3) = 7.607
2
k 2 = f x 0 + , y0 + k1 = f 1 + , 2+
2 2 2 2
h h 0.1 0.1
k3 = f x 0 + , y0 + k 2 = f 1 + , 2+ 7.607 = 7.873
2 2 2 2
h
yi +1 = yi + ( k1 + 2k2 + 2k3 + k4 )
6
0.1
y1 = y0 +
6
(6 + 2 ( 7.607) + 2 ( 7.873) + 10.118) = 2.785
At x = 1.1, y1 = 2.785
dy
= 3x 2 y
dx
y x
dy
∫
2
y ∫
= 3 x 2dx
xo
y 3(x 3 − x o3 )
ln = = x 3 − x o3
yo 3
Numerical Solution of ODEs 233
Rearrange
3
− xo3 3
−1
y = yoe x = 2e x
Table 7.3 lists the solution of the ODE in Example 7.4 using RK4 (step size, h = 0.1)
and the analytical solution. The RK4 calculations are in good agreement with the
analytical solution.
Change the setting to the fixed-value RK4 method as follows: after launching
Simulink, click on modeling in the toolbar, and then from the pulldown menu,
select Model/Setting. While on the configuration parameters page, change the
default values of the start time, stop time, type and solver, and fixed-step size to
those shown in Figure 7.21. The Simulink block diagram that graphically describes
the solution of the equation defined in Example 7.6 is shown in Figure 7.22.
Running the model outputs the value of y (21.48) in the Display at x =1.5.
The alternative way to use Simulink is embedding a MATLAB code into the
Simulink function block (Figure 7.23). The MATLAB function is attached to four
TABLE 7.3
Comparison of the Runge-Kutta Method and the Exact Solution of the ODE
Defined in Example 7.6
x k1 k2 k3 k4 yRK4 yexact
1.000 2.000 2.000
1.100 6.000 7.607 7.873 10.118 2.785 2.785
1.200 10.108 13.053 13.638 17.921 4.141 4.142
1.300 17.891 23.606 24.946 33.645 6.619 6.620
1.400 33.558 45.362 48.589 67.489 11.435 11.440
1.500 67.236 93.329 101.558 145.736 21.480 21.502
FIGURE 7.21 Model setting using fixed-step Runge-Kutta method, h = 0.1 (Example 7.6).
234 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 7.22 Simulink solution using fixed-step Runge-Kutta method of the ODE required
in Example 7.6.
FIGURE 7.23 Simulink block diagram symbolizes the solution using the RK4 method with
a stop time of five to the equation defined in Example 7.6.
input ports, lower limit interval ( x o ), upper limit interval ( x f ) , the step size (h), and
the initial conditions ( y0 ). The MATLAB function is connected to a display block
that releases the value of y at the stop time x.
The following program represents the MATLAB code utilizing the RK4 method
to solve the ODE required in Example 7.6. The MATLAB code is implanted in the
Simulink MATLAB function. The resultant ODE solution found in the Simulink dis-
play block is 21.48 at the independent variable stop time (i.e., x = 0.2).
k1 = f(xi, yi);
k2 = f(xi+h/2, yi+ h*k1/2);
k3 = f(xi+h/2, yi+k2*h/2);
k4 = f(xi+h, yi+k3*h);
k = k1+2*k2+2*k3+k4;
yf = yi + k*h/6;
yi=yf;
xi = xi +h;
end
Res=yi;
end
Python Solution
A Python code program that utilizes the RK4 method to solve an ODE in the
Python programming language is presented. In this Python program, x 0 and yo
represents the initial condition. x n is the calculation point on which the value of
yn corresponding to x n is to be calculated using the RK4 method. The step size is
h, which represents the number of finite steps before reaching to x n , desired value.
dy
= x + y2 , y ( 0 ) = 1
dx
Solution
dy
= x + y2
dx
f ( x, y) = x + y2 , y ( 0) = 1
At x1 = x 0 + h = 0 + 0.1 = 0.1
k1 = f ( x o , yo ) = x o + yo2 = 0 + 12 = 1
k1 = 1
Calculate k 2
h h 0.1 0.1
k 2 = f x o + , yo + k1 = f 0 +
, 1+ (1) = f ( 0.05, 1.1)
2 2 2 2
k 2 = 1.1525
Calculate k3
h 0.1 0.1
(1.1525) = f ( 0.05, 1.0576)
h
k3 = f x o + , yo + k 2 = f 0 + , 1+
2 2 2 2
k3 = 1.169
Calculate k 4
k 4 = 1.374
Numerical Solution of ODEs 237
Calculate y1 at x1
h
y1 = y0 + ( k1 + 2k2 + 3k3 + k4 )
6
0.1
y1 = 1 +
6
(1 + 2(1.1525) + 2(1.169) + 1.374 ) = 1.1165
y1 ( 0.1) = 1.1165
Hence
x1 = 0.1, y1 = 1.1165
Calculate y2 at x 2 = 0.2
Calculate k1:
Calculate k 2:
h k 0.1 0.1
k 2 = f x o + , yo + 1 = f 0.1 + , 1.1165 + 1.3466
2 2 2 2
Simplify
Calculate k3:
h h 0.1 0.1
k3 = f x o + , yo + k 2 = f 0.1 + , 1.1165 + 1.5514
2 2 2 2
Simplify
Calculate k 4
Simplify
Calculate y2
h
y2 = y1 +
6
{k1 + 2 ( k2 ) + 2 ( k3 ) + k4 }
h
y2 = y1 +
6
{1.3466 + 2 (1.5514 ) + 2 (1.5758) + 1.8233} = 1.2736
Hence, x 2 = 0.2, y2 = 1.12736.
While on the Simulink page, click on modeling, then model setting, and fill in the
following information, start time and stop time values of 0 and 0.2, respectively.
The solver type is set as a fixed type with a fixed-step size value of 0.1, as shown
in Figure 7.24.
The Simulink block diagram solution of Example 7.7 is shown in Figure 7.25,
and the obtained results agree with the manual calculations.
A diagram is created using Simulink’s built-in function (Figure 7.26). Example 7.7
can be solved in the following alternative method, which extracts the MATLAB code
from the Simulink diagram.
The following MATLAB code corresponds to the RK4 method planted in the
Simulink function for the solution of the following ODE solution (Example 7.7).
FIGURE 7.24 Model setting using the fixed step of 0.1 of the Runge-Kutta method for solv-
ing the ODE defined Example 7.7.
Numerical Solution of ODEs 239
FIGURE 7.25 Simulink solution with a stop time of 0.2 of the equation defined in Example 7.7.
FIGURE 7.26 Simulink solution using the RK4 method, a stop time equal to 5, of the equa-
tion defined in Example 7.7.
yi=yf;
xi = xi +h;
end
Res=yi;
end
Python Solution
The below Python program, followed by the execution results, corresponds to the
approximate numerical solution of Example 7.7 using the RK4 method.
h =0.1
step= h
print(‘\n--------SOLUTION--------’)
print(“at x= “, x0,” yn =”, y0)
# function to be solved
def f(x, y):
return x+y**2
# using RK4 formula
for i in range(n):
k1 = (f(x0, y0))
k2 = (f((x0+h/2), (y0+k1*h/2)))
k3 = (f((x0+h/2), (y0+k2*h/2)))
k4 = (f((x0+h), (y0+k3*h)))
k = (k1+2*k2+2*k3+k4)
yn = y0 + k*h/6
x0 = x0+h
print(“at x= “, x0,” yn =”, yn)
y0 = yn
dy
= f ( x, y)
dx
Integrate between limits, we get
y x
∫dy = ∫ f ( x, y) dx
y0 xo
Integrating,
x
∫
y = yo + f ( x , y ) dx
x0
∫
y1 = yo + f ( x , yo ) dx
x0
Numerical Solution of ODEs 241
∫
y2 = yo + f ( x , y1 ) dx
x0
∫
yn = yo + f ( x , yn−1 ) dx
x0
The Picard’s method generates a sequence of approximations as y1, y2, and y3 that
converges to the exact solution y ( x ) .
Determine the value of y at x = 0.3 of the following ODE using Picard’s iterative
approximation method.
dy
= x + y2 , y ( 0) = 0
dx
Solve manually and with Python and Simulink/MATLAB programming.
Solution
x x
x2
∫ ( )
y ( x ) = yo + f x + y 2 dx = yo + f ( x + 0 ) dx =
∫ 2
x0 x0
x x
x 2 0.32
∫
y1 ( 0.3) = yo + f ( x + 0 ) dx = 0 + xdx =
x0
∫
x0
2
=
2
= 0.045
2. Second iteration
2
dy x2 x4
= x + y12 = x + = x +
dx 2 4
Therefore,
0.3
x4
y2 ( x ) = yo +
∫
0
x + 4 dx
2
x x5 0.32 0.35
y2 = 0 + + =0+ + = 0.0451
2 20 2 20
242 Numerical Methods in Chemical Engineering Using Python® and Simulink®
3. Third iteration
dy
= x + y22
dx
2
dy x2 x5 x 4 2 x 7 x 10
= x+ + =x+ + +
dx 2 20 4 40 400
Therefore
0.3
x 4 x 7 x 10
y3 = 0 +
∫
0
x + 4 + 20 + 400 dx
2
x x5 x8 x 11 0.32 0.30.5 0.38 0.311
y3 = + + + = + + + = 0.0451
2 20 160 4400 2 20 160 4400
The Simulink block diagram for Example 7.8 is shown in Figure 7.27. The default
solver is used for RK4 as the Picard’s method is not built in MATLAB solver.
The alternative way to solve Example 7.8 is using the Simulink function, as
shown in Figure 7.28, to output the MATLAB code.
The following MATLAB codes correspond to the Picard’s method planted in
the Simulink function for the solution of the following ODE solution (Example 7.8).
FIGURE 7.27 Simulink’s solution, with downtime equal to 0.3, of the equation given in
Example 7.8.
Numerical Solution of ODEs 243
FIGURE 7.28 The block diagram of the simulation using the Picard method with a down-
time of 0.2 represents the solution of the equation given in Example 7.8.
Python Solution
y1(0.3) = 0.045
y2(0.3) = 0.045121499999999995
y3(0.3) = 0.045190091880681814
7.8 SUMMARY
Numerical methods are used to find numerical approximations to the solutions of
ODEs. Numerical integration includes a wide range of algorithms for calculating
the numerical value of a definite integral (the area under a curve between two fixed
terms). The numerical method with a minor error compared to the exact solution
is the most accurate and easiest to solve. The problem lies in those cases where
there is no exact solution. The approximate numerical solution of ODEs includes
Euler’s explicit and implicit methods, the Midpoint method, the Heun method, and
the Runge-Kutta method.
7.9 PROBLEMS
1. Using the Euler method, find an approximation for the solution of the dif-
ferential equation
dy
= f ( x, y)
dx
y ( x o ) = yo
dy
= 37.5 − 3.5y
dt
Initially, the orange concentration in the tank was 50 g/L. Using explicit Euler’s
method and a step size of h = 1.5 min, what is the orange concentration after
3 minutes? Compare the predicted result with the analytical solution. Find the
best step size that gives the closest result to the exact solution. The exact solu-
tion of the ODE is given by
dy y
= 1+
dx x
Numerical Solution of ODEs 245
With the initial condition, y (1) = 1, the approximate numerical answer is (3.38).
4. Solve the following ODE using the Picard iterative method with an initial
condition, y ( 0 ) = 100, calculate y(50)
dy
= 50 − 0.01y
dt
dy
= yx 3 − 0.01y, y ( 0 ) = 1.0
dx
dy
= yx 3 − 0.01y, y ( 0 ) = 1.0
dx
7. Using the Euler’s method within the range t = 0 to 2, solve the following
first-order initial value ODE, using a step size, h = 0.5
dy 2
= t y − 1.2y, y ( 0 ) = 1
dt
dy 2
= t y − 1.2y, y ( 0 ) = 1
dt
dy 2
= t y − 1.2y, y ( 0 ) = 1
dt
=
dy
= x − 1.2 y, y ( 0 ) = 1
dx
246 Numerical Methods in Chemical Engineering Using Python® and Simulink®
REFERENCES
8 Simultaneous Systems of
Differential Equations
In this chapter, we will learn how to simultaneously solve a system of binary, linear,
independent differential equations of the first order. Such systems arise when the
model includes two or more variables. This chapter grants numerical methods pro-
gramming for generating simple and effective Python and MATLAB codes along
with Simulink to output numerical solutions with the required accuracy. It uses the
plotting functions of Matplotlib in Python and the Plot function in MATLAB to pres-
ent the required results graphically.
LEARNING OBJECTIVES
1. Solve binary ODEs simultaneously using the Euler method.
2. Employ the Midpoint method to solve a system of ODEs simultaneously.
3. Use the fourth-order Runge-Kutta (RK4) method to solve binary ODEs.
4. Solve ODEs simultaneously using the Picard method.
8.1 INTRODUCTION
Numerical methods for solving ordinary differential equations (ODEs) are used to
find approximate numerical solutions for ODE. Their use is also known as a numeri-
cal integral, although this term can also refer to the computation of integrals [1]. A
first-order differential equation with only the first derivative of the dependent vari-
able (e.g., y) without higher derivatives is considered an initial value problem (IVP),
dy
= y ′ ( x ) = f ( x , y ( x ) , y ( x o ) = yo (8.1)
dx
dy1
= f1 ( t , y1 , y2 ) , y1 ( 0 ) = y1,0 (8.2)
dt
dy2
= f2 ( t , y1 , y2 ) , y2 ( 0 ) = y2,o (8.3)
dt
The Euler algorithms for solving the stated two ODEs are as follows:
The following example illustrates the application of the explicit Euler method in solv-
ing two ODEs simultaneously.
Solve the following two ODEs simultaneously using the Euler method and a step
size of 0.1.
dy1
= − y1e1−t + 0.8y2 , y1 ( 0 ) = 0
dt
dy2
= y1 − y23 , y2 ( 0 ) = 2
dt
Manually calculate the values of the dependent variables ( y1 , y2 ) within the inter-
val [0, 3]. Compare the manual calculations with the approximate solutions using
Simulink (the graphical programming of MATLAB) and Python programming of the
Euler method.
Simultaneous Systems of Differential Equations 249
Solution
dy1
= f1 ( t , y1 , y2 ) = − y1e1− x + 0.8y2
dx
dy2
= f2 ( t , y1 , y2 ) = y1 − y23
dx
( )
y1,1 = 0 + hf1 ( 0, 0,2 ) = 0 + 0.1 −0e1− 0 + 0.8 ( 2 ) = 0.16
At t = 0.2,
( )
Simplify
(
y2,2 = 1.2 + hf2 ( 0.1,0.16,1.2) = 1.2 + 0.1 0.16 − (1.2 ) = 1.043
3
)
The rest of the calculations are listed in Table 8.1.
TABLE 8.1
Euler’s Method Solution of Example 8.1
Time (t) i y1 y2
0.000 0 0.000 2.000
0.100 1 0.160 1.200
0.200 2 0.217 1.043
2.800 28 1.067 0.953
2.900 29 1.126 0.973
3.000 30 1.187 0.994
250 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 8.1 Simulink solver configuration parameters for selecting the Euler method to
solve the equations defined in Example 8.1.
FIGURE 8.2 Numerical solution of the two equations defined in Example 8.1 applying the
explicit Euler method in Simulink.
Simulink Solution
To use the integrator block function from the Simulink library, the configuration
parameters such as start time, stop time, type, and solver should be changed in the
modeling set. Therefore, to do so, while on the Simulink simulation page, click on
the modeling tab, and select the modeling setting. Change the start and stop times
to 0.1 and 3, respectively. For the solver selection, indicate the type: fixed step and
the solver: Euler, as shown in Figure 8.1. The entire Simulink graphical solution of
the two ODEs defined in Example 8.1 using the explicit Euler method is presented
in Figure 8.2. The values in the display blocks are the values of y1 and y2 with a
stop time of three.
Individuals may want to change the background colors of the scope before
copying the scale image. To do so, click on the ‘scope parameters’ icon (the
Simultaneous Systems of Differential Equations 251
FIGURE 8.3 Simulink plot of the numerical solution utilizing the explicit Euler method of
the model equations defined in Example 8.1.
second icon) and go to the ‘style’ tab. Change the shape color to black, the axes
colors to white background and black writing, and the font color to black. After
the modifications, the plot of the two ODEs generated by Simulink is shown in
Figure 8.3. There is no option to automatically set the axis or name labels in the
plot generated by the scope simulated graph. However, after the simulation, a per-
son can manually add axis names from the Graphical User Interface (GUI) shape
or the command window. Select the scope graph from Simulink and run the fol-
lowing commands into the command window.
set(0,’ShowHiddenHandles’, ‘on’)
set(gcf, ‘menubar’, ‘figure’)
These commands will enable the toolbar in the scope graph shape window. One
can add axis names from Insert>> X Label and Insert>> Y Label. To change the
legend, while in the scope window, select the View > Legend option to display dif-
ferent variables to show the legend. If one double-clicks on a legend, a small text
entry field will appear, allowing one to name it. After the scope amendment, the
graph should look like that in Figure 8.3.
An alternative way to solve the equations defined in Example 8.1 is to use the
Simulink MATLAB function (Figure 8.4). The MATLAB function requires writing a
MATLAB code. Figure 8.4 shows the Simulink MATLAB function with five input
ports: the lower limit interval (a), the upper limit interval (b), the step size (h), and
the initial values of y1 ( yo ) and y2 ( z o ). The two displays release the values of y1 and
y2 at the simulation stop time [3].
252 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 8.4 Simulink numerical solution of the two equations described in Example 8.1
using the Euler method. The stop time is three.
FIGURE 8.5 Simulink generated a plot of numerical solution using the explicit Euler
method of the equations described in Example 8.1.
The following program is the MATLAB code implanted in the Simulink MATLAB
function shown in Figure 8.4. When running the Simulink graphical program, it
generates the plot presented in Figure 8.5. The figure describes the change in the
dependent variables ( y1 , y2 ) with time within the desired interval [0, 3].
Python Solution
The following is the Python code that utilizes the Euler method simultaneously for
solving the two ODEs defined in Example 8.1. Numerical methods with Python
programming allow the creation of simple and efficient Python code that produces
numerical solutions with the required degree of accuracy. Use of matplotlib plot-
ting functions to present the results graphically [3]. The implementation of the
program resulted in Figure 8.6.
FIGURE 8.6 Python plot represents the numerical solution using the Euler method of the
equations defined in Example 8.1.
# initial conditons
y1 = 0.0
y2 = 2
for x in xp:
yp.append(y1)
up.append(y2)
m1 = h*F1(y1, y2, x)
k1 = h*F(y1, y2, x)
y1+= m1
y2+= k1
# plot section
plt.plot(xp, yp, ‘r-’, label=r’$y_{1}$’)
plt.plot(xp, up, ‘b--’, label=r’$y_{2}$’)
plt.xlabel(“Time”, fontsize=14)
plt.ylabel(‘y ‘, fontsize=14,rotation=0)
plt.legend()
plt.grid(True)
dy1
= f1 ( x , y1 , y2 ) (8.6)
dx
dy2
= f2 ( x , y1 , y2 ) (8.7)
dx
Simultaneous Systems of Differential Equations 255
The Midpoint algorithm for solving the two equations at once is as follows:
h h h
k2,1 = f1 xi + , yi ,1 + k1,1 , yi ,2 + k2,1 (8.10)
2 2 2
h h h
k2,2 = f2 xi + , yi ,1 + k2,1 , yi ,2 + k2,2 (8.11)
2 2 2
Finally,
Apply the Midpoint method to solve the following two ODEs using a step size of 0.1.
dy1
= − y1e1−t + 0.8y2 , y1 ( 0 ) = 0
dt
dy2
= y1 − y23 , y2 ( 0 ) = 2
dt
Calculate y1 and y2 manually within the interval [0, 3] and confirm your manual
calculations with Python and Simulink graphical programming.
Manual Solution
k1,1
k1,2
k 2,1
h h h
k 2,1 = f1 to + , yo,1 + k1,1 , yo,2 + k1,2
2 2 2
k 2,2
h h h
k 2,2 = f2 to + , yo,1 + k1,1 , yo,2 + k1,2
2 2 2
Accordingly
y1 = y1,0 + h ( k 2,1 )
y2 = y2,0 + h × k 2,2
The remaining values are calculated using excel and tabulated in Table 8.2.
Figure 8.7 shows the excel plot of the numerical solution utilizing the Midpoint
method. It shows the change in the dependent variables (y1 and y2) versus time (t).
Simultaneous Systems of Differential Equations 257
TABLE 8.2
Solution of Binary Equation Defined in Example 8.2 Using the Midpoint
Method
i x k1,1 k1,2 k2,1 k2,2 y1 y2
1 0.000 0.000 2.000
2 0.100 1.600 –8.000 1.073 –4.016 0.107 1.598
3 0.200 1.015 –3.976 0.750 –2.583 0.182 1.340
29 2.900 0.597 0.193 0.609 0.195 1.196 1.000
30 3.000 0.621 0.197 0.633 0.198 1.260 1.020
FIGURE 8.7 Excel plot of the manual calculations, utilizing the Midpoint method, of the
equations defined in Example 8.2.
Simulink Solution
FIGURE 8.8 Simulink solution utilizing MATLAB function and the Midpoint method of
the two ODEs defined in Example 8.2, stop time equal three.
FIGURE 8.9 Simulink plot generated using the Midpoint method of the two equations
defined in Example 8.2.
% Enter RHS of the first ODE
f2=@(x, y, z) (y-z^3);
x=a:h:b;
y=zeros(1,length(x));
z=zeros(1,length(x));
Simultaneous Systems of Differential Equations 259
FIGURE 8.10 Python-generated plot using the Midpoint method represents the solution of
the equations defined in Example 8.2.
y(1)=y0;
z(1)=z0;
x(1)=a;
for i=1:(length(x)-1)
k1 = f1(x(i), y(i), z(i));
m1 = f2(x(i), y(i), z(i));
k2 = f1(x(i)+0.5*h, y(i)+0.5*h*k1,z(i)+0.5*h*m1 );
m2 = f2(x(i)+0.5*h, y(i)+0.5*h*k1,z(i)+0.5*h*m1 );
y(i+1) = y0 + h*k2;
y0=y(i+1);
z(i+1) = z0 + h*m2;
z0=z(i+1);
end
y1f=y0;
y2f=z0;
% Plot sections
plot(x, y, x, z, ‘linewidth’, 1.5);
text(0.5,1.05, ‘\leftarrow z’, ‘color’, ‘r’, FontSize=15)
text(0.45,0.25, ‘\leftarrow y’, ‘color’, ‘b’, FontSize=15)
text(1.0,1.45, ‘Midpoint method’, FontSize=15)
xlabel(‘Time’, FontSize=15);
ylabel(‘y_1, y_2’, FontSize=15);
grid on
The following is the Python program that employed the Midpoint method to solve
two ODEs defined in Example 8.2. Running the program releases the plot of the
dependent variables versus the independent variable, as shown in Figure 8.10.
# Example 8.2
# Midpoint method for solving two ODEs
import matplotlib.pyplot as plt
import numpy as np
from numpy import arange
# Enterthe two functions
260 Numerical Methods in Chemical Engineering Using Python® and Simulink®
dy1
= f1 ( t , y1 , y2 ) (8.14)
dt
dy2
= f2 ( t , y1 , y2 ) (8.15)
dt
h h h
k2,1 = f1 ti + , yi ,1 + k1,1 , yi ,2 + k1,2 (8.18)
2 2 2
h h h
k2,2 = f2 ti + , yi ,1 + k1,1 , yi ,2 + k1,2 (8.19)
2 2 2
h h h
k3,1 = f1 ti + , yi ,1 + k2,1 , yi ,2 + k2,2 (8.20)
2 2 2
h h h
k3,2 = f2 ti + , yi ,1 + k2,1 , yi ,2 + k2,2 (8.21)
2 2 2
where h > 0 is a step size parameter, I = 1, 2, 3,…, the RK4 method is given by:
h
yi ,1 = yi −1,1 +
6
{k1,1 + 2k2,1 + 2k3,1 + k4,1 } (8.24)
h
yi ,2 = yi −1,2 +
6
{k1,2 + 2k2,2 + 2k3,2 + k4,2 } (8.25)
The Runge-Kutta method provides greater precision than multiplying each function
in ODE by the step size factor and adding the results to the current values in y (such
as the Euler method).
Solve the following two ODEs simultaneously using RK4 and a step size of 0.1.
dy1
= − y1e1−t + 0.8y2 , y1 ( 0 ) = 0
dt
dy2
= y1 − y23 , y2 ( 0 ) = 2
dt
Solution
h h h
k 2,1 = f1 to + , yo,1 + k1,1 , yo,2 + k1,2
2 2 2
h h h
k 2,2 = f2 to + , yo,1 + k1,1 , yo,2 + k1,2
2 2 2
h h h
k3,1 = f1 to + , yo,1 + k 2,1 , yo,2 + k 2,2
2 2 2
h h h
k3,2 = f2 to + , yo,1 + k 2,1 , yo,2 + k 2,2
2 2 2
0.1 0.1
(1.07314 ) , 2 + ( −4.016)
0.1
k3,2 = f2 0 + , 0+
2 2 2
calculate y1,1
h
y1,1 = y1,0 +
6
{k1,1 + 2k2,1 + 2k3,1 + k4,1 }
0.1
y1,1 = 0 +
6
{1.6 + 2 (1.073) + 2 (1.3) + 0.8186} = 0.1194
Calculate y1,2
h
y2,1 = y2,0 +
6
{k1,2 + 2k2,2 + 2k3,2 + k4,2 }
0.1
y2,1 = 2 +
6
{−8 + 2 ( −4.016) + 2 ( −5.77) − 2.751} = 1.4946
Table 8.3 summarizes the manual calculations of the first step (i.e., x1 = 0.1). The
remaining values are calculated using Excel, listed in Table 8.4. Figure 8.11 is a plot
of the data obtained from the excel calculations.
Simulink Solution
Before performing the Simulink block diagram solution of the equations described
in Example 8.3, we must change the configuration parameters to RK4 (through the
modeling/model setting). The changes include the start time, the stop time, the
type, the solver selection, and the fixed step size (Figure 8.12). The Simulink graph-
ical programming (utilizing the RK4 method) of the equations defined in Example
8.3 is illustrated in Figure 8.13. The figure shows the values of the dependent
TABLE 8.3
Manual Calculation Using RK4 and Step Size, h = 0.1
k1 k2 k3 k4
i x k1,1 k1,2 k2,1 k2,2 k3,1 k3,2 k4,1 k4,2 y1 y2
0 0 0 2
1 0.1 1.6 –8 1.073 –4.016 1.3 –5.77 0.81865 –2.751 0.119 1.4946
264 Numerical Methods in Chemical Engineering Using Python® and Simulink®
TABLE 8.4
The Following Is the Excel Solution
i t k11 k1,1 k1,2 k2,2 k3,1 k3,2 k4,1 k4,2 y1 y2
0 0 0 2
1 0.1 1.600 –8.000 1.073 –4.016 1.301 –5.771 0.818 –2.751 0.119 1.495
2 0.2 0.902 –3.219 0.682 –2.207 0.748 –2.499 0.563 –1.734 0.192 1.255
3 0.3 0.578 –1.786 0.466 –1.364 0.495 –1.457 0.402 –1.125 0.240 1.113
4 0.4 0.407 –1.137 0.346 –0.916 0.361 –0.957 0.311 –0.776 0.275 1.018
5 0.5 0.313 –0.780 0.279 –0.648 0.287 –0.669 0.260 –0.557 0.304 0.952
29 2.9 0.595 0.195 0.607 0.196 0.607 0.197 0.619 0.198 1.186 0.996
30 3 0.619 0.198 0.632 0.199 0.632 0.200 0.644 0.201 1.249 1.016
FIGURE 8.11 Plot of the manual calculations utilizing the RK4 method for solving the two
ODEs defined in Example 8.3.
FIGURE 8.12 Simulink solver setting to RK4 method for solving the equations defined in
Example 8.3.
Simultaneous Systems of Differential Equations 265
FIGURE 8.13 Simulink solution using the RK4 method of the two ODEs specified in
Example 8.3.
variables (y1 , y2) at the simulation stop time (i.e., 3). Figure 8.14 shows the Simulink
graphical programming solution utilizing the RK4 method of the twin ODEs speci-
fied in Example 8.3.
Figure 8.15 shows the graphical programming in Simulink using the MATLAB
function from the Simulink library as an alternative way. Following the figure is the
MATLAB code implanted in the MATLAB function. The following MATLAB pro-
gram is linked to the Simulink MATLAB function (Figure 8.15). Figure 8.16 shows
the plot of the two ODEs described in Example 8.3. The Simulink MATLAB func-
tion is fed with five input constants representing the lower limit interval (a), upper
limit interval (b), step size (h), and the initial values of y1 ( yo ) and the initial value
of y2 ( z o ) . The two output displays the values of the dependent variables (y1 and y2)
at the simulation stop time (3).
FIGURE 8.14 Simulink solution utilizing RK4 to solve the two ODEs defined in Example
8.3.
FIGURE 8.15 Simulink simultaneous solution using RK4 of the two ODEs described in
Example 8.3. Stop time is equal to three.
Simultaneous Systems of Differential Equations 267
FIGURE 8.16 Simulink plot generated utilizing RK4 of the twin equations defined in
Example 8.3.
Python Solution
The ‘SciPy’ method is used for solving the required set of equations defined in
Example 8.3, and it now has ‘solve _ ivp ’. This solves the system on the interval
(0,3) with an initial value (0,2). The result has an independent value (t in the nota-
tion) as ‘res.t’. These values were chosen automatically. One can provide ‘teval ’ to
have the solution evaluated at desired points: for example,
FIGURE 8.17 Plot of dependent variables ( y1 and y2 ) against the time generated by the
Python program to solve Example 8.3.
#Example 8.3
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
# enter the model equations
def rhs(t, y):
return [-y[0]*np.exp(1-t)+0.8*y[1], y[0]-y[1]**3]
# enter the initial conditions as shown below
res = solve_ivp(rhs, (0, 3), [0,2])
print (res.t)
t_eval=np.linspace(0, 3)
print (res.y)
plt.plot(res.t, res.y.T)
plt.ylabel(r’$y_{1}, y_{2}$’, fontsize=14)
plt.grid(True)
plt.xlabel(‘Time’, fontsize=14)
The following Python code is programmed using RK4 syntax to solve these two
types of ODEs defined in Example 8.3. The results are in good agreement with
those obtained from the solver of the IVP (solveivp ). Execution of the Python pro-
gram results in the plot disclosed in Figure 8.18. The Python code presented here
is for the RK4 method in two dimensions.
# Example 8.3
# Runge Kutta method
import matplotlib.pyplot as plt
import numpy as np
from numpy import arange
Simultaneous Systems of Differential Equations 269
FIGURE 8.18 Python solution using RK4 of the two ODEs given in Example 8.3.
# y’ = -y*np.exp(1-x)+0.8*u
# u’ = y-u**3
def F1(y, u, x):
return -y*np.exp(1-x)+0.8*u
def F(y, u, x):
return y-u**3
a = 0
b = 3
N =30
h = (b-a)/N
xp = arange(a, b, h)
yp = []
up = []
# initial conditons
y = 0.0
u = 2
for x in xp:
yp.append(y)
up.append(u)
m1 = h*F1(y, u, x)
k1 = h*F(y, u, x) #(x, v, t)
m2 = h*F1(y+0.5*m1, u+0.5*k1, x+0.5*h)
k2 = h*F(y+0.5*m1, u+0.5*k1, x+0.5*h)
m3 = h*F1(y+0.5*m2, u+0.5*k2, x+0.5*h)
k3 = h*F(y+0.5*m2, u+0.5*k2, x+0.5*h)
m4 = h*F1(y+m3, u+k3, x+h)
k4 = h*F(y+m3, u+k3, x+h)
y += (m1 + 2*m2 + 2*m3 + m4)/6
u += (k1 + 2*k2 + 2*k3 + k4)/6
# plot section
plt.plot(xp, yp, ‘r-’, label=’$y_{1}$’)
plt.plot(xp, up, ‘b-.’, label=’$y_{2}$’ )
plt.xlabel(‘Time’, fontsize=14)
plt.ylabel(r’$y_{1}, y_{2}$’, fontsize=14)
plt.legend()
plt.grid(True
270 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Let
dy
= f ( x, y, z ) , with y ( x o ) = yo (8.26)
dx
and
dz
= g ( x , y, z ) , with z ( x o ) = zo (8.27)
dx
where z and y are dependent variables on x (independent). Using the Picard method,
the value of yn and zn is given as
yn = yo +
∫ f ( x, y
xo
n −1 , zn−1 ) dx (8.28)
and
∫
zn = zo + g ( x , yn−1 , zn−1 ) dx
xo
(8.29)
y1 = yo +
∫ f ( x, y , z ) dx
xo
o o (8.30)
Simultaneous Systems of Differential Equations 271
and
∫
z1 = zo + g ( x , yo , zo ) dx
xo
(8.31)
y2 = yo +
∫ f ( x, y , z ) dx
xo
1 1 (8.32)
and
∫
z2 = zo + g ( x , y1 ,z1 ) dx
xo
(8.33)
y3 = yo +
∫ f ( x, y , z ) dx
xo
2 2 (8.34)
and
∫
z3 = zo + g ( x , y2 ,z2 ) dx
xo
(8.35)
Using the Picard method, find an approximate value of y and z at x = 0.1 for the
following two ODEs
dy
= x + z, y ( 0 ) = 2
dx
dz
= x − y2 , z ( 0 ) = 1
dx
Solution
Applying Picard’s method for solving the following two ODEs together is as follows:
At x = 0
dy
= x + z = f ( x , y, z )
dx
dz
= x − y 2 = g ( x, y, z )
dx
∫
yn = yo + f ( x , yn −1 , z n −1 ) dx
xo
∫
z n = z o + g ( x, yn −1 , z n −1 ) dx
xo
x x
∫
y1 = yo + f ( x , x o , z o ) dx = 2 +
xo
∫ f ( x + z ) dx
xo
o
x
x2
y1 ( x ) = 2 +
∫ ( x + 1) dx = 2 + x + 2
xo
Substitute x = 0.1
0.1
x2 0.12
y1 ( 0.1) = 2 +
∫ ( x + 1) dx = 2 + x + 2
0
= 2 + 0.1 +
2
= 2.105
Calculate z at x = 0.1
x x
∫
z1 = z o + g ( x, yo , z o ) dx = 1 +
xo
∫ ( x − y ) dx
xo
2
o
x
2
∫ ( x − 2 ) dx = 1 + 2
x
z1 ( x ) = 1 + 2
− 4x
0
Simultaneous Systems of Differential Equations 273
Substitute x = 0.1
0.1
2
0.12
∫ ( x − 2 ) dx = 1 + 2
x
z1 ( 0.1) = 1 + 2
− 4x = 1 + − 4 ( 0.1) = 0.605
2
0
∫
y2 = yo + f ( x , y, z ) dx
xo
x x
x2
y2 = 2 +
∫
0 0
∫
( x + z1 ) dx = 2 + x + 1 − 4 x + dx
2
x2 x3
y2 ( x ) = 2 + x − 3 +
2 6
Substitute x = 0.1
0.12 0.13
y2 ( 0.1) = 2 + 0.1 − 3 + = 2.085
2 6
∫
z 2 = z o + g ( x , y1 , z1 ) dx
xo
∫
z 2 = z o + g ( x , y1 , z1 ) dx
xo
= 1+
∫ ( x − y ) dx
0
2
1
x
x2
2
0
∫
= 1 + x − 2 + x + dx
2
x
x4
∫
= 1 + x − 4 − x2 −
0
4
− x 3 − 2 x 2 dx
x2 x 3 x 5 x 4 2x 3
= 1+ − 4x − − − −
2 3 20 4 3
274 Numerical Methods in Chemical Engineering Using Python® and Simulink®
Substitute x = 0.1
3rd approximation (n = 3)
∫
y3 = yo + f ( x , y2 , z2 ) dx
xo
y3 = 2 +
∫ ( x + z ) dx
xo
2
x
3x 2 x4 x5
y3 = 2 +
∫0
x + 1 − 4x − 2 − x − 4 − 20 dx
3
3x 2 x 3 x 4 x 5 x6
y3 = 2 + x − − − − −
2 2 4 20 120
Substitute x = 0.1
For z
∫
z3 = z o + g ( x , y2 , z 2 ) dx
xo
z3 = 1 +
∫ ( x − y ) dx
0
2
2
x
3x 2 x 3
2
z3 = 1 +
∫
0
x − 2 + x −
2
+ dx
6
Integrate
3x 2 5 x 3 7x 4 31x 5 x 6 x7
z3 = 1 − 4x − + + − + −
2 2 12 60 12 252
Simultaneous Systems of Differential Equations 275
FIGURE 8.19 Simulink solution using the Simulink integrator with default solver of the
equation defined in Example 8.4, the stop time is 0.1.
Finally,
z3 ( 0.1) = 0.587
Simulink Solution
y =y3(a);
z =z3(a);
Python Solution
The following is the Python code utilized by the Picard method to solve the two
ODEs defined in Example 8.3.
#Picard’s Method
#
276 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 8.20 Simulink solution using Picard’s method of the equations defined in Example
8.4 and a stop time of three.
def y1(x):
Y1 = 2+x+x**2/2
return Y1
def z1(x):
z1 = 1 + x**2/2 - 4*x
return z1
def y2(x):
Y2 = 2 + x - 3*x**2/2 + x**3/6
return Y2
def z2(x):
z2 = 1+x**2/2 -4*x-x**3/3-x**5/20 - x**4/4 - 2*x**3/3
return z2
def y3(x):
Y3 = 2 + x - 3*x**2/2-x**3/2-x**4/4 -x**5/20-x**6/120
return Y3
def z3(x):
z3 = 1–4*x - 3*x**2/2 +5*x**3/2+7*x**4/12–31*x**5/60+x**6/12-x**7/252
return z3
#
print (‘ ‘)
print (‘ === Solution ===’)
print (‘for dy(x) = x + y^2 , dz(x)=x-y^2, the results are :’)
print (‘--------------------------------------’)
print (‘y1(0.1) = ‘, “%.3f”%y1(0.1))
print (‘y2(0.1) = ‘, “%.3f”%y2(0.1))
print (‘y3(0.1) = ‘, “%.3f”%y3(0.1))
print (‘z1(0.1) = ‘, “%.3f”%z1(0.1))
print (‘z2(0.1) = ‘, “%.3f”%z2(0.1))
print (‘z3(0.1) = ‘, “%.3f”%z3(0.1))
y3(0.1) = 2.084
z1(0.1) = 0.605
z2(0.1) = 0.604
z3(0.1) = 0.588
8.3 SUMMARY
Numerical methods of ODEs are used to find a numerical approximation of solutions
simultaneously to two ODEs. The chapter goes through the numerical integration
methods, including Euler, Midpoint, the RK4, and the Picard as appropriate meth-
ods for solving two ODEs simultaneously. The numerical integration methods were
graphically programmed using Simulink and coded using Python.
8.4 PROBLEMS
1. Solve the following two first-order initial value ODEs using the Euler
method. Using a step size of 0.1, find the value of x and y at t= 0.3. verify
the solution using Simulink and Python.
dx
= 3 x + 8 y, x ( 0 ) = 6
dt
dy
= −x − 3 y, y ( 0 ) = −2
dt
Answer: 6.782, –2.060
dy1
= 3 y1 − 4 y2 , y1 ( 0 ) = 1
dx
dy2
= y1 − y2 , y2 ( 0 ) = 0
dx
Answer: 2.155, 0.4029
dy
= 3 y + 4 x, y ( 0 ) = 0
dt
dx
= −4 y + 3 x , x (0) = 1
dt
Answer: –1.87, 4.075
278 Numerical Methods in Chemical Engineering Using Python® and Simulink®
4. Using the RK4 method, solve the following two first-order initial value
ODEs using a step size of 0.1 to find the value of x and y at x = 0.3. Validate
the manual results using Simulink and Python programming.
dy1
= y2 , y1 ( 0 ) = 0
dt
dy2
dx
( )
= 10 1 − y12 y2 − y1 , y2 ( 0 ) = 1
5. Utilizing the RK4 method, solve the following two first-order initial value
ODEs representing the concentration of components A and B in a batch
reactor using a step size of 0.1 to find the value of C A and C B at t = 0.5.
Confirm the manual solution using Simulink and Python programming.
The values of the rate constants, k1 = 0.1, k2 = 0.2 .
dC A
= −k1C A , C A ( 0 ) = 1
dt
dC B
= k1C A − k2C B , CB ( 0 ) = 0
dt
Answer: 0.95, 0.046
dy1
= y2 , y1 ( 0 ) = 1
dx
dy2
= x 3 ( y1 + y2 ) , y2 ( 0 ) = 0.5
dx
Answer: 1.4896, 0.8500
REFERENCES
1. Atkinson, K., Han, W., and Stewart, D., 2009, Numerical Solution of Ordinary
Differential Equations. Newyork: John Wily.
3. Kong, Q., Siauw, T., and Bayen, A., 2021, Python Programming and Numerical
Methods: A Guide for Engineers and Scientists. California, CA: Academic Press.
9 Boundary Value
Problems of Ordinary
Differential Equations
A boundary value problem (BVP) is a system of ordinary differential equations
(ODEs) with a solution and derivative values defined at more than one point. This
chapter uses finite differences and shooting methods to convert BVPs into algebraic
equations. Furthermore, the Thomas algorithm is presented and explained in this
chapter. Manual calculations are compared to Python and Simulink programming
predictions, where the code is given for each case.
LEARNING OBJECTIVES
1. Identify a BVP.
2. Implement the shooting method to solve a BVP.
3. Apply the finite difference method.
4. Use the Thomas algorithm to solve a BVP.
5. Utilize Python and Simulink/MATLAB to tackle a BVP.
9.1 INTRODUCTION
A differential equation is defined as an equation that relates one or more unknown
functions and their derivatives in mathematics. ODEs can only be solved given addi-
tional information, called boundary conditions (BCs). If the BCs are specified at the
same independent variable value (e.g., x), the problem is an initial value problem
(IVP). Some BCs are specified at different values for the independent variable, such
as initial and final positions of x; these are called BVPs. The differential equation
contains one or more terms and the derivatives of one dependent variable concerning
another independent variable [1]. We often see them for problems where conditions
are specified at various locations in space rather than time.
dy
= f (x) (9.1)
dx
dy
= 5x (9.2)
dx
FIGURE 9.1 Schematic of a rod fixed between two plats with different temperatures.
A differential equation contains derivatives that are either partial derivatives or ordi-
nary derivatives. BVPs commonly arise in many engineering subjects, such as heat
transfer, mass transfer, and reactor design. An example of the BVP is the steady-state
temperature distribution along a rod hung between two plates of different tempera-
tures (Figure 9.1). A BVP comprises a differential equation subject to a given set of
BCs. BCs are prescribed for the unknown variable and its derivatives at more than
one point [2].
An example of a second-order BVP is shown below:
d2y
= y( x ) (9.3)
dx 2
y ( 0 ) = 0, y (1) = 1
Note that the number of BCs equals the order of the ODE. In this example, the given
interval is [0, 1]. Then the number of subintervals, n,
b−a
n=
h
For h = 0.25
1− 0
n= =4
0.25
The aim is to find y ( 0.25) , y ( 0.5) , y ( 0.75), if h = 0.25. From the BCs, y ( 0 ) and y (1)
are known (Figure 9.2).
Every ordinary or partial derivative occurring in the equation and the BCs is
replaced by finite difference approximation. Accordingly, the equation is reduced to
Boundary Value Problems of ODEs 281
FIGURE 9.2 Schematic dividing the main interval [0, 1] into four subintervals.
a set of linear systems of equations, which are then solved using standard methods.
The following sections describe initial and BCs.
d2y dy
2
+2 + y = e −2x (9.4)
dx dx
The initial conditions are at one point of the independent variable ( x = 0),
dy
y ( 0 ) = 1, ( 0 ) = 2.5
dx
d2y dy
+2 + y = e −2x (9.5)
dx 2 dx
dy y − yi
= y′ = i +1 (9.6)
dx h
dy y − yi −1 y ( x ) − y ( x − h ) Present − Previous
= y′ = i = = (9.7)
dx h h h
Central finite difference, also called the central difference approximation for y ′ ( x )
dy y − yi −1 y ( x + h ) − y ( x − h ) Next − Previous
= y′ = i +1 = = (9.8)
dx 2h 2h 2×h
d2y y − 2 yi + yi −1 y ( x + h ) − 2 y ( x ) + y ( x − h )
2
= y′′ = i +1 = (9.9)
dx h2 h2
Figure 9.3 describes the forward finite difference methods and central and backward
formulas.
Follow the steps below to solve the BVP using the finite differences method:
1. Divide the interval between the initial and boundary value into n intervals.
2. Use the finite difference approximation method to replace the derivatives.
3. Solve the generated set of algebraic equations resulting from the finite dif-
ference approximation to obtain the solution to the BVP.
Boundary Value Problems of ODEs 283
ai yi −1 − bi yi + ci yi +1 = ri
Solve the following BVP using the finite difference approximation approach apply-
ing four subintervals (n = 4).
d2y dy
+2 + y = x2
dx 2 dx
Solve the BVP manually, using Python and Simulink graphical programming
language.
284 Numerical Methods in Chemical Engineering Using Python® and Simulink®
TABLE 9.1
Thomas Algorithm for Solvent Tridiagonal Matrix
β1 = b1
γ1
γ1 =
β1
For i = 2,..., n
c −1
βi = bi − ai i
βi − 1
γ − ai γ i −1
γi = i
βi
yn = γ n
End
For j = 1,..., n − 1
yn − j +1
yn − j = γ n − j − cn − j
βn− j
End
Solution
Divide the interval [0, 1] into four subintervals (n = 4), and hence h = 0.25.
Using finite central difference formulas,
d 2 y yi +1 − 2 yi + yi −1
=
dx 2 h2
dy yi +1 − yi −1
=
dx 2h
yi +1 − 2 yi + yi −1 y − yi −1
+ 2 i +1 + yi = xi2
h2 2h
yi +1 − 2 yi + yi −1 + h ( yi+1 − yi −1 ) + h 2 yi = h 2 x 2
Rearrange
(1 − h ) yi −1 + ( h 2 − 2) yi + (1 + h ) yi +1 = h 2 x 2
Boundary Value Problems of ODEs 285
Divide by (1 − h)
Solve for i = 1 to 3
Rearrange (previous y1 , present y2, next y3) and consider the substitution of the
known initial y0 and boundary value y4
In matrix form,
A.Y = B
The solution was obtained using the Python code shown below:
A = np.array([A1,A2 , A3])
B = np.array([-0.146, 0.0156, -0.9648])
286 Numerical Methods in Chemical Engineering Using Python® and Simulink®
X = np.linalg.inv(A).dot(B)
print(“”)
print(X)
The following calculated values of y1 , y2, and y3 are generated from the Python
program after execution.
Simulink Solution
The BCs
The Simulink predicted results (Figure 9.4) agree with the manual calculations used
in solving the three linear algebraic equations.
Using the Simulink MATLAB function, an alternative Simulink solution uses the
finite difference method by discretizing the ODE. The second-order BVP
d2y dy
+2 + y = x2
dx 2 dx
Discretizing the second-order ODE into a tridiagonal matrix by using the finite dif-
ference formula for the second derivative,
d 2 y y ( i + 1) − 2y ( i ) + y ( i − 1)
=
dx 2 h2
dy y ( i + 1) − y ( i − 1)
=
dx 2h
y ( i + 1) − 2 y ( i ) + y ( i + 1) y ( i + 1) − y ( i + 1)
+ y (i) = x (i)
2
+2 ×
h2 2h
Boundary Value Problems of ODEs 287
FIGURE 9.4 Simulink block diagram for the solution of the BVP defined in Example 9.1.
Arranging,
1 1 2 1
y ( i + 1) 2 + +y ( i ) − 2 + 1 +y ( i + 1) 1 − = x ( i )
2
h h h h
1 1
supd = +
h2 h
2
maind = +1
h2
1
supd = 1 −
h
288 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 9.5 Simulink block diagram using finite difference method for solving the BVP
specified in Example 9.1.
Figure 9.5 is the Simulink block diagram followed by the MATLAB codes embed-
ded into the Simulink MATLAB function, illustrating the finite difference method
solution of Example 9.1. The MATLAB function contains four input ports that rep-
resent the interval lower and upper limit (xlim), BC 1 ( y0 ), BC 2 ( y1 ), and the num-
ber of intervals (n). The exit port displays the results at each grid point.
The following MATLAB codes are associated with the Simulink MATLAB func-
tion and solve the ODE using an indicated discretization. Using MATLAB, the
results are drawn in Figure 9.6.
FIGURE 9.6 Solution of the BVP defined in example 9.1 using finite difference method and
the Simulink MATLAB function.
Python Solution
In the finite difference method, the derivatives of the differential equation are
approximated using the finite difference equations. Python solution generates
Figure 9.7 while using the finite difference method discretizing the BVP of Example
9.1. The following Python program uses the finite difference method to solve the
BVP equation using the finite difference approximation method. The values of y
are shown below, and the entire data are plotted in Figure 9.7.
import numpy as np
import matplotlib.pyplot as plt
# (1-h)y_(i-1)+(h^2-2)y_i+(1+h)y_(i+1)=h^2 x^2
a=0
b=1
n = 4
h = (b-a) / n
# Matrix coefficient
A = np.zeros((n+1, n+1))
A[0, 0] = 1
A[n, n] = 1
290 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 9.7 Python solution using the BVP finite difference method described in
Example 9.1.
# matrix coefficient
x = np.linspace(a, b, n+1)
for i in range(1, n):
A[i, i-1] = 1-h
A[i, i] = h*h-2
A[i, i+1] = 1+h
#print(A)
x = np.linspace(a, b, n+1)
b = np.zeros(n+1)
b[0]=0.2 # boundary conditon 1
for i in range(1, n):
b[i] = h**2*x[i]**2
b[n] = 0.8 # boundary condtion 2
#print(b)
# solve the linear equations
y = np.linalg.solve(A, b)
plt.figure(figsize=(8,5))
plt.plot(x, y, ‘ro-’)
plt.plot(a, b[0], ‘bo’), plt.plot(1, 0.8, ‘bo’)
plt.xlabel(‘x’), plt.ylabel(‘y’)
plt.grid(True)
print (y)
Execution
Solve the following second-order BVP using the finite difference approximation
method with h = 0.5 within the interval [1, 3].
d2y x
= 1− y + x; y(1) = 2, y(3) = −1
dx 2 5
FIGURE 9.8 Describes the subintervals used to solve the BVP defined in Example 9.2.
Solution
Using a step size of 0.5, as stated in the problem statement (h = 0.5), resulting in
four subintervals, as shown in Figure 9.8.
There are five nodes with h = 0.5: y0, y1 , y2, y3, and y4. However, there are only
three unknowns since y0, y4 are known:
Discretizing the equation in the finite difference form, the ODE becomes
yi +1 − 2 yi + yi −1 xi
− 1 − yi = xi i = 1, 2, 3, 4
h2 5
x
yi +1 − 2 yi − h 2 1 − i yi + yi +1 = h 2 xi
5
x
yi +1 − 2 + h 2 1 − i yi + yi +1 = h 2 xi
5
Substitute, i = 1, 2, 3
i = 1, x1 = 1.5
1.5
y0 − 2 + 0.52 1 − y1 + y2 = 0.5 × 1.5
5
i = 2, x 2 = 2.0
2
y1 − 2 + 0.52 1 − y2 + y3 = 0.52 × 2.0
5
i = 3, x3 = 2.5
2.5
y2 − 2 + 0.52 1 − y3 + y4 = 0.52 × 2.5
5
292 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 9.9 Simulink block diagram for the solution of BVP stated in Example 9.2.
After simplifying and substituting the BC, y0 = 2, y4 = −1, the following three linear
algebraic equations arise:
−2.175y1 + y2 + 0 = −1.625
y1 − 2.15 y2 + y3 = 0.5
0 + y2 − 2.125 y3 = 1.625
Solve the three unknowns in the linear algebraic equations by any means. The
answer is as follows:
Simulink Solution
The linear algebraic equations are solved using Simulink and the Thomas algo-
rithm shown in Figure 9.9, followed by the MATLAB code embeds the Simulink
function block. Figure 9.9 discloses the results plotted in Figure 9.10.
d2y x
− 1 − y = x; y(1) = 2, y(3) = −1
dx 2 5
After the substitution of the finite difference formulas, the discretized equation is
yi +1 − 2 yi + yi −1 x
− 1 − i yi = xi
h 2 5
Boundary Value Problems of ODEs 293
Rearranging,
x
y(i + 1){1} + y(i) −2 − 2 1 − i h 2 + y(i − 1) = h 2 x (i)
5
supd = 1
x
maind = −2 − 2 1 − i h 2
5
subd = 1
rhs = xh 2
Simulink Solution
Finite difference methods (FDMs) are numerical methods for solving Partial
Differential Equations (PDE) by approximating them with difference equations,
where finite differences approximate the derivatives. Thus, FDMs are discre-
tionary methods. FDMs convert linear or nonlinear ODE/ Partial Differential
Equation (PDE) into a system of linear (nonlinear) equations, which matrix algebra
294 Numerical Methods in Chemical Engineering Using Python® and Simulink®
The Thomas algorithm is utilized to obtain the solution for the tridiagonal matrix
system.
The equations are solved using Simulink and the Thomas algorithm (Figure 9.11),
followed by the MATLAB code describing the Thomas algorithm, followed by the
executed results illustrated in Figure 9.12.
By double-clicking the MATLAB function block, the following MATLAB code is
appended to the Simulink block:
FIGURE 9.11 Simulink block diagram using Thomas algorithm for the solution of the BVP
presented in Example 9.2.
FIGURE 9.12 Simulink plot for the solution of Example 9.2, red circle is the BCs; blue
circles are calculated y values at the three nodes.
r(1)=r(1)-ya;r(n)=r(n)-yb;
beta=c;gam=c;y=c;
beta(1)=b(1);gam(1)=r(1)/beta(1);
for i=2:n
beta(i)=b(i)-a(i)*c(i-1)/beta(i-1);
gam(i)=(r(i)-a(i)*gam(i-1))/beta(i);
end
y(n)=gam(n);
for j=1:n-1
y(n-j)=gam(n-j)-c(n-j)*y(n-j+1)/beta(n-j);
end
grid on
Res = [ya, y(1), y(2), y(3), yb];
Python Solution
Figure 9.13 presents the python solution of the set of equations generated using
the finite difference method of Example 9.2. The four y values followed the python
program are at the studied x values. The y values shown below the Python program
results after executing the python program are the same as those obtained manu-
ally and by Simulink. Figure 9.13 displays the plotted data bounded by the BCs at
x (1) = 2 and x ( 2 ) = −1. The curve could be smoother if decreasing the step size.
FIGURE 9.13 Python solution for the BVP defined in Example 9.2.
Boundary Value Problems of ODEs 297
import numpy as np
import matplotlib.pyplot as plt
a=1
b=3
n = 4
h = (b-a) / n
# Matrix coefficient
A = np.zeros((n+1, n+1))
A[0, 0] = 1
A[n, n] = 1
# matrix coefficient
x = np.linspace(1, 3, n+1)
for i in range(1, n):
A[i, i-1] = 1
A[i, i] = -(2+h**2*(1-x[i]/5))
A[i, i+1] = 1
print(A)
x = np.linspace(1, 3, n+1)
b = np.zeros(n+1)
b[0]=2 # boundary conditon 1
for i in range(1, n):
b[i] = h**2*x[i]
b[n] = -1 # boundary condtion 2
print(b)
# solve the linear equations
y = np.linalg.solve(A, b)
plt.figure(figsize=(9,6))
plt.plot(x, y, ‘ro-’)
plt.plot(1,2,’bo’), plt.plot(3, -1, ‘bo’)
plt.xlabel(‘x’, fontsize=24)
plt.ylabel(‘y’, fontsize=24,rotation=0)
plt.yticks(fontsize=16)
plt.xticks(fontsize=16)
plt.savefig(‘image.jpg’)
plt.grid()
print (y)
Execution results
Solve the following second-order differential equation using the finite difference
approximation method,
d2y
= 1 − y,
dx 2
Boundary conditions
y ( 0 ) = 0, y (1) = 0
Solution
Using the finite difference approximation formulas, replace the derivatives with the
finite difference as follows:
yi +1 − 2 yi + yi −1
+ yi − 1 = 0
h2
Multiply by h 2
yi +1 − 2 yi + yi −1 + h 2 yi − h 2 = 0
yi +1 + (h 2 − 2) yi + yi −1 − h 2 = 0
yi +1 − 1.875 yi + yi −1 − 0.0625 = 0
Substitute i = 0 (known BC 1)
yo = 0
Substitute i = 1
y2 − 1.938 y1 + y0 − 0.0625 = 0
Substitute i = 2
y3 − 1.938 y2 + y1 − 0.0625 = 0
Substitute i = 3
y4 − 1.938 y3 + y2 − 0.0625 = 0
Substitute i = 4 known BC 2
y4 = 0
After substituting the BCs, solve the set of three linear algebraic equations to fined
y1 , y2 , y3
y2 − 1.938 y1 + 0 − 0.0625 = 0
y3 − 1.938 y2 + y1 − 0.0625 = 0
0 − 1.938y3 + y2 − 0.0625 = 0
Boundary Value Problems of ODEs 299
There are three equations and three unknowns (the degree of freedom is zero).
Polymath and any other solver can quickly solve the equations:
Simulink Solution
The three linear algebraic equations can be solved using the algebraic constraint
function in Simulink under Math Operations. The Simulink block diagram is shown
in Figure 9.14.
An alternative Simulink solution uses the MATLAB function (Figure 9.15). Using
finite difference approximation formulas, replace the derivatives with the finite
difference.
yi +1 − 2 yi + yi −1
+ yi − 1 = 0
h2
Multiply by h 2
yi +1 − 2 yi + yi −1 + h 2 yi − h 2 = 0
FIGURE 9.14 Solution of three linear algebraic equations using the algebraic constraints
function in Simulink (Example 9.3).
300 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 9.15 Simulink block diagram represents the solution using the finite difference
method of the equation defined in Example 9.3.
{ }
y ( i + 1) {1} + y ( i ) −2 + h 2 + y ( i − 1) = h 2
rhs = h 2
FIGURE 9.16 Simulink-generated plot using the finite difference method represents the
equation defined in Example 9.3.
Python Solution
The following results were generated by Python of the set of algebraic equations
produced by the finite difference method:
[0.0 – 0.10467706 – 0.1403118 – 0.10467706 0.0]
The curve depicted in Figure 9.17 could be smoother if more grids were used
(increase n). The python code is shown as follows:
import numpy as np
import matplotlib.pyplot as plt
plt.style.use(‘seaborn-poster’)
a=0
b=1
n = 4
h = (b-a) / n
# Matrix coefficient
A = np.zeros((n+1, n+1))
302 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 9.17 Python solution using the finite difference method of the equation described
in Example 9.3.
A[0, 0] = 1
A[n, n] = 1
# matrix coefficient
x = np.linspace(0, 1, n+1)
for i in range(1, n):
A[i, i-1] = 1
A[i, i] = h**2-2
A[i, i+1] = 1
print(A)
x = np.linspace(0, 1, n+1)
b = np.zeros(n+1)
b[0]=0 # boundary conditon 1
for i in range(1, n):
b[i] = h**2
b[n] = 0 # boundary condtion 2
print(b)
# solve the linear equations
y = np.linalg.solve(A, b)
plt.figure(figsize=(9,6))
plt.plot(x, y, ‘ro-’)
plt.plot(0,0,’bo’)
plt.plot(1, 0, ‘bo’)
plt.xlabel(‘x’)
plt.ylabel(‘y’, rotation=0)
plt.grid()
converts a BVP into an equivalent IVP. Then, the IVP is solved via a trial-and-error
approach. This technique is called a ‘shooting’ method, by analogy to the procedure
of shooting an object at a stationary target (Figure 9.18). The following procedure is
recommended to follow in solving a BVP using the shooting method:
1. Start with a guess value for the auxiliary conditions at one point in time.
2. Solve the IVP using the numerical integration methods, Euler, and Runge-
Kutta methods.
3. Check if the BCs are satisfied, otherwise modify the guess, and resolve the
problem.
4. Use interpolation in updating the guess.
Demonstrate the shooting method for the steady-state heat transfer in a rod fixed
between two plates of differential temperatures. The rod is a length of 10 cm. The
following second-order ODE describes the model equation.
d 2T
= −0.05 ( 200 − T )
dx 2
Solution
1. Apply the shooting method and divide second-order BVP into two IVPs.
Let
dT
z=
dx
It can be written as
dT
= z, T ( 0 ) = 300
dx
dz d 2 T
= = −0.05 ( 200 − T ) , z ( 0 ) = guess
dx dx 2
Applying the Euler method for solving the two initial value ODEs
simultaneously.
Ti +1 = Ti + hf1 ( xi , Ti , zi )
zi +1 = zi + hf2 ( xi , Ti , zi )
Simulink Solution
The same data can be obtained using Simulink. Since we are using the Euler
method, the solver in Simulink should be changed to a fixed value step size and
the Euler method, as shown in Figure 9.19. Click on the modeling tab, then the set-
ting, then fill in the start, stop time, the type to fixed step, and for the solver, select
Euler, and enter the step as stated in the problem statement.
Figure 9.20 shows the Simulink block diagram. The initial guess found by excel
(−10.8232) is used for the same purpose as an initial guess for z integrator. The
temperature profile is shown in Figure 9.21.
TABLE 9.2
Solution Using the Shooting Method of Equation Defined in Example 9.4
i x T z
0 0 300 –7 (Initial guess)
1 1 300 + 1 * (–7) = 293 –7 + 1 * (–0.05 * (200–300) = –2
2 2 293 + 1 * (–2) = 291 –2 + 1 * (–0.05 * (200–293) = 2.65
3 3
9 9
10 10 400 (Target)
Boundary Value Problems of ODEs 305
TABLE 9.3
Solution of Two IVPs Simultaneously Using the Euler Method
i x T z
0 0 300.00 –10.82
1 1 289.18 –5.82
2 2 283.35 –1.36
3 3 281.99 2.80
4 4 284.79 6.90
5 5 291.70 11.14
6 6 302.84 15.73
7 7 318.56 20.87
8 8 339.43 26.80
9 9 366.23 33.77
10 10 400.00 42.08
FIGURE 9.19 Setting the Simulink solver to the Euler method and step size, h = 1.
Python Solution
The solution of Example 9.4 using Python is plotted as shown in Figure 9.22. A
trial and error of the initial guess value of z are required. The shooting methods are
developed to convert ODE BVPs into equivalent IVPs, and then we can solve them
using the methods we learned from the previous chapter. In the IVPs, we can start
from the initial value and move forward to get the solution.
306 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 9.20 Represents the Simulink block diagram for solving the algebraic equations
generated from the shooting method using the Euler method in Example 9.4.
FIGURE 9.21 Plot generated from the scope for the solution of the equation in Example 9.4.
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
x = np.linspace(0, 10, 100)
def equations(x, y):
yprime = np.zeros(2)
# Shooting method, desired equations
yprime[0] = y[1]
yprime[1] = -0.05*(200- y[0])
return yprime
tol = 1e-6
Boundary Value Problems of ODEs 307
max_iters = 1000
low = -10
high = 10
count = 0
while count <= max_iters:
count = count + 1
xspan = (x[0], x[-1])
# Set the initial condition
y0 = [300, -13.24]
# Solve the system using our guess
sol = solve_ivp(equations, xspan, y0, t_eval = x)
# Extract the function values from the solution object.
y_num = sol.y[0, :]
# Plot the solution
plt.plot(x, y_num, ‘b-’, label=‘Numeric’)
plt.plot([0, 10], [300,400], ‘ro’)
print(y_num[-1])
plt.grid(True)
plt.xlabel(‘x’, fontsize=24)
plt.ylabel(‘y’, fontsize=24,rotation=0)
plt.yticks(fontsize=16)
plt.xticks(fontsize=16)
plt.xlim((0,10))
plt.ylim((250,400))
Use the shooting method and solve the following second-order BVP within the
interval [1, 2].
d2y
= 6x , y (1) = 2, y ( 2 ) = 9
dx 2
Solution
First, we will convert the second-order ODE to two first-order ODEs IVPs, let
dy
= z , y (1) = 2
dx
dz
= 6x , z (1) = 2 ( Guess )
dx
Now we have two IVPs, and as a first approximation, we used the Euler method.
dy
= f1 ( x , y, z ) = z
dx
dz
= f 2 ( x , y, z ) = 6 x
dx
x1 = x 0 + h = 1 + 0.5 = 1.5
We are implementing the Euler method for solving two ODEs simultaneously.
yi +1 = yi + hf1 ( xi , yi , zi )
zi +1 = zi + hf2 ( xi , yi , zi )
Substitute
x o = 1, yo = 2, z o = 2
x1 = 1.5, y1 = 3, z1 = 5
TABLE 9.4
Assume z(0) = 0 as an Initial Guess
i xi yi zi
0 1 2 2
1 1.5 3 5
2 2.0 5.5 9.5
TABLE 9.5
Assume z0 = 5.5 as an Initial Guess
i xi yi zi
0 1.0 2.0 5.5
1 1.5 4.75 8.5
2 2.0 9.0 13.0
FIGURE 9.23 Solver setting of the configuration parameters page, for Example, 9.5 (Euler,
fixed step size).
Since y ( 2 ) = 5.5, the first trial initial guess ( z o = 2) is leading to not correct BC
( y ( 2 ) = 9). A second trial guess, z o = 5.5, based on this initial value guess for z, the
results are listed in Table 9.5. The shooting method converged at y ( 2 ) = 9 .
Simulink Solution
First, from the modeling page in the toolbar, click on model/setting. Change the
default setting of the configuration parameters. Set for the type: select fixed step;
for the solver, select: mode1 (Euler) (Figure 9.23). The Simulink block diagram
describing the solution of Example 9.5 is presented in Figure 9.24.
310 Numerical Methods in Chemical Engineering Using Python® and Simulink®
FIGURE 9.24 Simulink block diagram using Euler and the desired fixed step size of the
equations defined in Example 9.5.
Python Solution
A trial and error for the initial guess value of the hypothetical model equation in
Example 9.5. The results are plotted in Figure 9.25. The shooting method reduces
the BVP to the IVP. It is a common way to solve two-point BVPs.
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
x = np.linspace(1, 2, 100)
def equations(x, y):
yprime = np.zeros(2)
yprime[0] = y[1]
yprime[1] = 6*x
return yprime
tol = 1e-6
max_iters = 100
low = -10
high = 10
count = 0
while count <= max_iters:
count = count + 1
xspan = (x[0], x[-1])
# Set the initial condition vector to be passed into the solver
y0 = [2, 2.9]
# Solve the system using our guess
sol = solve_ivp(equations, xspan, y0, t_eval = x)
# For ease of use, extract the function values from the
solution object.
y_num = sol.y[0, :]
Boundary Value Problems of ODEs 311
Use the shooting method and the explicit Euler method to approximate the solu-
tion to the BVP:
d2y
= 2y, y ( 0 ) = 1.2, y (1) = 0.9, h = 0.25
dx 2
Confirm the manual results with Python programming.
Solution
The basic idea of the shooting method is that we take the second-order ODE and
write it as a system of the first-order ODE. Accordingly, split the second-order
ODE BVP into two IVPs.
dy
= z = f1 ( x , y, z ) , y ( 0 ) = 1.2
dx
dz
= 2 y = f2 ( x , y, z ) , z ( 0 ) = guess
dx
312 Numerical Methods in Chemical Engineering Using Python® and Simulink®
TABLE 9.6
Solution Using Shooting and Euler’s Methods of the
Equations Defined in Example 9.6
i xi y z
0 0 1.2 –1.0834
1 0.25 0.92915 –0.4834
2 0.5 0.8083 –0.01883
3 0.75 0.803594 0.385325
4 1 0.899925 0.787122
y1 = y0 + 0.25 f1 ( 0,1.2,−1.0834 )
z1 = z o + 0.25 f2 ( 0,1.2,−1.0834 )
Python Solution
Figure 9.26 displays the results of a trial and error for the hypothetical ODE.
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
x = np.linspace(0, 1, 4)
def equations(x, y):
yprime = np.zeros(2)
# the desired ODE(BVP) d2y/dx2=2y, dy/dx=z, dz/dx = 2y
yprime[0] = y[1]
yprime[1] = 2*y[0]
return yprime
tol = 1e-6
max_iters = 100
low = -10
high = 10
count = 0
while count <= max_iters:
count = count + 1
xspan = (x[0], x[-1])
# Set the initial condition vector to be passed into the solver
y0 = [1.2,-1.25]
# Solve the system using our guess
sol = solve_ivp(equations, xspan, y0, t_eval = x)
Boundary Value Problems of ODEs 313
# For ease of use, extract the function values from the solution
object.
y_num = sol.y[0, :]
# Plot the solution
plt.plot(x, y_num, ‘ro-’, label=‘Numeric’)
plt.plot (0,1.2, ‘bo’), plt.plot(1,0.9, ‘bo’)
print(y_num[-1])
plt.grid(True)
plt.xlabel(‘x’), plt.ylabel(‘y’)
plt.xlabel(‘x’, fontsize=24)
plt.ylabel(‘y’, fontsize=24,rotation=0)
plt.yticks(fontsize=20)
plt.xticks(fontsize=18)
plt.xlim((0,1.2))
plt.ylim((0.7,1.3))
In the following solution, the initial guess of the z value is determined by Python
without the initial guess trial-and-error solution (Figure 9.27).
FIGURE 9.27 Python solution where the function found the initial guess.
xa, xb = 0, 1
xini = np.linspace(xa, xb, 11) # determine x Initial value of
yini = np.zeros((2, xini.size)) # determine y Initial value of
res = solve_bvp(dydx, boundCond, xini, yini) # solve BVP
xSol = np.linspace(xa, xb, 100) # Output mesh node
ySol = res.sol(xSol)[0] # At mesh nodes y value
# plot section
plt.plot(xSol, ySol, ‘r-’)
plt.plot(0,1.2, ‘bo’)
plt.plot(1, 0.9, ‘bo’)
plt.grid()
plt.xlabel(‘x’, fontsize=24)
plt.ylabel(‘y’, fontsize=24,rotation=0)
plt.yticks(fontsize=20)
plt.xticks(fontsize=18)
plt.xlim((-0.05,1.1))
plt.ylim((0.7,1.3))
9.4 SUMMARY
This chapter discusses the numerical solution of ODEs and BVPs. The BVPs specify
the value of the dependent variable at the boundaries. Use strategies for IVPs to solve
BVPs. The shooting method requires guessing an initial condition that substitutes for
a BC and iterates to find the proper solution.
9.5 PROBLEMS
1. Solve the following BVP using the shooting method; after splitting the equa-
tion, use the explicit Euler method (step size, h = 1) to perform the numerical
integration of the two IVPs simultaneously.
d2y
= 2 y − 8 x + 72, y ( 0 ) = 0, y ( 9 ) = 0
dx 2
Boundary Value Problems of ODEs 315
316 Numerical Methods in Chemical Engineering Using Python® and Simulink®
REFERENCES
1. Ascher, U.M., Mattheij, R.M., and Russell, R.D., 1995, Classics in Applied Mathematics,
Numerical Solution of Boundary Value Problems for Ordinary Differential Equations.
Philadelphia: Society for Industrial and Applied Mathematics.
2. Polyanin, A.D., and Zaitsev, V.F., 2003, Handbook of Exact Solutions for Ordinary
Differential Equations. Boca Raton: Chapman & Hall/CRC Press.
Appendix A
Python Programming Code
A.2 INTRODUCTION
There are several rules that programmers follow in writing programming codes. The
list of rules are as follows:
1. Aim for a smaller number of code lines; if 10 lines can do the same task as
20 lines, then why the extra complexity and lines of code to run?
2. Aim for simpler code; program codes should be easily read and understood
by different programmers since different programmers could work on the
same code.
3. Aim for explicit rather than implicit code; the code should be clearly and
fully expressed, leaving nothing implied.
4. Aim for flat code rather than nested code; for example, in the ‘if’ function,
it is better to keep the code flat than nested, and the line’s starting point
keeps getting further and further.
5. Aim for sparse lines of code; having dense code is not favorable, and a
straightforward sparse program is easier to work with.
6. Aim for readability; take into consideration other programmers working
on the same code.
Writing Python code with these guidelines in mind will help the programmer’s code
to be more efficient, simpler, easier to understand, and require less computational
time.
317
318 Appendix A
A.3 SETTING UP
In this book, the program Spyder is used to write the code. Spyder is a free and open-
source tool that is written in Python to run Python codes. It features an interactive
user interface and beautiful visualization capabilities. Spyder has several compo-
nents and can be updated with any plugin, thus increasing the possibility of adding
more functions to the program. Spyder is available for Windows, MacOS, and Linux
for free. The latest version of Python is 3.9.5, released on May 3, 2021.
In this book, Spyder is employed to write Python programs. Spyder is a powerful
Interactive Development Environment (or IDE) for the Python programming lan-
guage. Figure A.1 shows the Spyder user interface.
To check for the current Python version on windows as an example, a simple code
is used:
import sys
print(“User Current Version:-”, sys.version)
After setting up the program and learning the rules of coding, the basics of Python
can be introduced. In every programming language, the first function taught is
responsible for displaying “Hello world!” on the screen. This can be easily done in
Python with one line of code as follows:
print(“Hello world!”)
When running the code, you should see the following output:
Hello world!
As can be seen from the results, the parentheses are not displayed but are required
when writing the code to indicate what is the required text. When the editor reads the
function print, it will display whatever is inside the parenthesis. Getting started with
Python a basic function is taught at first, the ‘print’ function. The print function can
be used in any place where a message is to be displaced.
In writing comments:
‘#’ hashtag is used to indicate the start of a comment.
If a comment stretches over many lines:’’ is written at the start, then ’’’ indicates
the comment end, and those lines will not be executed when command is run.
Other mathematical functions are also present in Python, but to activate them, the
math class must be imported into the Python code. The functions can then be used
as follows:
from math import * #to import class
print(cos(90)) #to solve cosine value in radians
print(pi) #pi represent pi value of a circle
print(e) #e represent euler’s number
#Results:
-0.4480736161291701
3.141592653589793
2.718281828459045
There are other mathematical functions in Python, as shown in the following table.
Python can store variables and assign a specific value to them as follows:
x = 2 #defining variable x
y = 2 #defining variable y
z = ‘hey’ #variable can be defined as string
#variables can be utilized in anyway possible
print(x+y)
print(x*y)
print(x/y)
print(z)
#Results:
4
4
1.0
Hey
An important function of coding is the ability to input information; this can be done
with ‘input’ function. When ‘input’ function is used with text, the text is displayed,
and the program waits for an input from the user to continue. An example utilizing
‘input’ function is as follows:
Appendix A 321
The if function can be extended and other conditions can be added with ‘elif’ func-
tion, which stands for ‘else if’, and if the input doesn’t follow any condition, a ‘else’
function is added. The previous example can be extended as follows:
The ‘for’ loop statements can be saved with every repetition, as follows:
a = 0
for x in range(6):
a = a+x
print(x)
print(a)
#Results:
0
1
2
3
4
5
15 #The sum of all x values
Another loop used in Python is the ‘while’ loop, which executes a group of state-
ments while the condition remains true and only stops when the condition is false.
An example is as follows:
Appendix A 323
x = 1
while x < 100: #condition
x = x*2
print(x)
#Results:
2
4
8
16
32
64
128 #statements are run until condition is false
There are several logical expressions to be used with ‘if’ statements and loops and
are shown in the following table:
== Is it equal
!= Is not equal
< Less than
<= Less than or equal
> More than
>= More than or equal
Combining the logical expressions with other operators can be very useful.
Examples of operators are shown in the following table:
Operator Meaning
and Combines conditions and all have to be true
or Anyone of the conditions can be true
not Outputs ‘True’ if the expression is false
Loops can go forever, therefore loop controls are needed. Loop controls are shown
in the following table:
Function Meaning
break Terminates the loop
continue Ends the current iteration and moves forward
pass Used as placeholder for future code
324 Appendix A
Operator Meaning
int(x) Converts x into an integer
float(x) Converts x into a floating number
xEy E is the mathematical × 10 y
x ** y ** is the exponential
J Complex number
Complex number can be used in Python using ‘j’ to identify the complex number
and value of −1. An example of complex number as follows:
x = 1+2j
z = 2j
sum = x + z
print(sum)
#Results
(1+4j) #complex numbers are added
a.6.1 strINgs
When defining a variable as a string, it can still use ‘+’ operator, as follows:
x = ‘Hello’ #defining as a string
y = ‘How are you’
z = x + ‘,‘ + y #adding variables
print(z) #print function
#Results:
Hello, How are you
A print function could be across several lines by using three quotes as follows:
print(“‘Hello
My name is Nayef
It is nice to meet you”‘)
#Results
Hello
My name is Nayef
It is nice to meet you
Appendix A 325
In a string, each character is numbered starting from zero. This is shown in the
following examples.
Example 1:
x = “Apple”
for y in range(7):
print(x[y])
#Results
A
P
P
L
e
Example 2:
x = “0123456789”
print(x[0]) #starts from 0
print(x[1]) #1 is the second character in the string
print(x[1:4]) #1, 2, and 3 are included
print(x[6:10])
#Results
0
1
123
6789
There are function used with strings in Python as shown in the following table:
Operator Meaning
len(string) Shows the number of characters in a string
str(string) Identifies the variable as a string
x = “0123456789”
y = “CRC press”
z = 5
print(len(x)) #len shows number of characters
print(len(y))
c = z + 4
print(c) #to prove c is treated as a number
p = str(z) + ‘ ‘ + x #str treats a variable as a string
print(p)
#Results
10
9
9
5 0123456789
326 Appendix A
When writing a print function, the ‘%’ operator can be used to include either a
number or a specific string. The following example illustrates the point.
x = 1
y = ‘One’
print(“One is %d” %x)
print(“1 is %s” %y)
#However writing the code as follows is wrong
#print(“1 is %d” %y) #output an error
#Results
One is 1
1 is One
for k in CarColors.keys():
print(k, “: “, CarColors[k])
#Results
Togg: Red
Camry: Black
Tesla: White
Hyundai: Silver
Mercedes: Gold
BMW: Blue
Lists and dictionaries can be copied. For a list, the function ‘list’ is used to copy
e.i. I2 = list(I1). For copying the dictionary, the function ‘list.copy()’ is used.
Functions are objects that can be assigned to a variable, as a parameter, and returned
from a function. Functions require the () after them, and this is what distinguishes
them from variables.
def names(name):
print(“Hello “ + name)
names(“Name1”)
names(“Name2”)
names(“Name3”)
#Results
Hello Name1
Hello Name2
Hello Name3
If the number of arguments is unknown, add ‘*’ before the parameter name.
Example as follows:
def kids(*names):
print(“The youngest child is “ + names[2])
kids(“OLd”, “Middle”, “Youngest”)
#Results
The youngest child is Youngest
A
330 Appendix A
#Results
Hello\
Hello Hey
Hello
N
Hello “
Index 0 1 2 3 4 5 6 7
Character M o h a m e d “Space”
Function Meaning
capitalize Capitalizes the first word
center Centers a string
casefold Makes all lowercase
count(‘x’) Counts how many “x”
endswith(“x”) Checks if ends with x
find(“x”) True or false if string ends with x
upper Makes all characters upper case
lower Makes all characters lower case
for x in “Tesla”:
print(x)
#Results
T
e
s
l
a
Using the link and call method, people can create classes and share them with differ-
ent people. A class might sound similar to a module, but the difference is that a class
is used to define a blueprint for a given object, whereas a module is used to reuse a
given piece of code inside another program.
The __init__() function:
All classes have a function called __init__(), which is always executed when the
class is being initiated. An example of the init function is as follows:
class information:
def __init__(self, name, age): #the self reference is needed
self.name = name
self.age = age
T = information(“Name1”,24)
print(T.name)
print(T.age)
#Results
Name1
24
Appendix A 333
def myfunc(self):
print(“I am “+ self.name + “\n Nice to meet you.”) #works with
strings
T = information(“Mohamed”, 24)
T.myfunc()
#Results
I am Mohamed
Nice to meet you.
The “self” is used in the examples, but it can be anything specified by the user. The
objective of the first variable is to reference the current instance of the class. As can
be seen in the following example:
class information:
def __init__(anything, name, age):
anything.name = name
anything.age = age
def myfunc(anything):
print(“Hello “+ anything.name + “\n Nice to meet you.”)
#works with strings
T = information(“John”,63)
T.myfunc()
#Results
Hello John
Nice to meet you.
Modifications can be done to the class, and there are three main operators as shown
in the following example.
class information:
def __init__(anything, name1, name2, name3):
anything.name1 = name1
anything.name2 = name2
anything.name3 = name3
def first(anything):
print(“I am “+ anything.name1)
def second(anything):
print(“I am “+ anything.name2)
def third(anything):
print(“I am “+ anything.name3)
name1 = list[0]
name2 = list[1]
name3 = list[2]
T.first()
T.second()
T.third()
T.name2 = “NMG” #things can be assigned
T.second()
#del T.name1 can be used to delete
#Results
I am Name1
I am Name2
I am Name3
I am NMG
In classes, the user can define any function so that Python’s built-in operators can
also be utilized.
A.11 CONCLUSION
Appendix A introduced Python, starting from setting up the program to explaining
all the functions used in Python. Each function method of working is explained, and
examples are provided to show actual results. The objective is to explain the main
functions possible, but this information can be used and extended to no boundaries.
This provides foundations, but there is no limit set for the users and their creativity
and applications.
Appendix B
Introduction to Simulink
335
336 Appendix B
The Sources icon yields the library shown in Figure B.6. The most used source is
‘Clock’, which is used to generate a time vector.
The ‘Sinks’ icons are shown in Figure B.7. The ‘Scope’ is the most common block
used for plotting signals from a specific variable in the Simulink block diagram.
The Math library contains math functions block (Figure B.8).
338 Appendix B
TC = ( TF − 32 ) / 1.8
Solution
To create this model, you need to drag and drop the blocks into the model from
the following Simulink block libraries:
Next, gather the blocks into the model window (Figure B.11)
dy 2
= y + t 2 , y (1) = 1
dt t
Solution
2 x + y − 2z = 3
x− y−z = 0
x + y + 3z = 12
Solution
AX = B
2 1 −2 x 3
1 −1 −1 y = 0
1 1 3 z 12
2 1 −2 x 3
1 −1 −1 y − 0 =0
1 1 3 z 12
Simulink Solution
Open the new Simulink page and select the blocks shown in Figure B.13.
Select the gain, double click, and input the matrix in the Gain windows
(Figure B.14).
[2 1-2; 1-1-1; 1 1 3]
Multiplication: Matrix(K*u) (u vector)
Select constant, double click, and enter the constant as shown in Figure B.15.
dy 1 3
= 2 y + , y (1) = −2
dt t t
Build the Simulink block diagram and run it for the range of 1–4 seconds
(Figure B.16).
Appendix B 343
Solution
Set the modeling simulation period between 0 and 4. The setting of the configura-
tion parameters can be modified through MODELING/Model setting (Figures B.17
and B.18).
344 Appendix B
d2y dy
+ 3 + 40 y = 0
dt 2 dt
dy 1
y ( 0 ) = 1, (0) =
dt 3
Simulink Solution
Rearrange the second-order ODE such that the term with the highest order on the
left side equals the rest of the terms.
d2y dy
= −3 − 40y
dt 2 dt
FIGURE B.19 Simulink solution of the second order ODE of Example B.4.
Appendix B 347
FIGURE B.22 Simulink solution of the polynomial equation presented in Example B.6.
5x 6 + 4 x 4 − 5x 3 = 10
Solution
5x 6 + 4 x 4 − 5x 3 − 10 = 0
5x + 4 y − 5z = −5
3 x − 8 y + 2 z = 10
7 x − 4 y − z = −14
Appendix B 349
Solution
5 x + 4 y − 5z + 5 = 0
3 x − 8 y + 2 z − 10 = 0
7 x − 4 y − z + 14 = 0
The solution of the set of algabriac equations are solved in Figure B.23.
An alternative way is to put it in Matrix form is as follows:
AX − B = 0
5 x + 4 y − 5z + 5 = 0
3 x − 8 y + 2 z − 10 = 0
7 x − 4 y − z + 14 = 0
5 4 −5 x −5
3 −8 2 y − 10 =0
7 −4 −1 z −14
FIGURE B.24 Simulink alternative solution of the algebraic equations defined in Example
B.7.
The more straightforward solution and using the matrix structure, the Simulink
block diagram of Example B.7 is represented in Figure B.24.
x2 − x − 2 = 0
Solution
Using the Simulink Algebraic Constraint function, one of the roots is found (-1), as
shown in Figure B.25.
3 x 3 + 5sin ( x ) − 7cos ( 2 x ) = 0
Appendix B 351
Solution
Figure B.26 shows the Simulink Algebraic Constraint function for solving a polyno-
mial equation with trig functions (i.e., sin(x), cos(2x)).
FIGURE B.26 Simulink solution of the cos and sin function of Example B.9.
Index
Note: Bold page numbers refer to tables and italic page numbers refer to figures.
“Algebraic Constraint” block 92, 114 constant coefficient 344
algebraic equations 283, 339, 342 continuous stirred tank reactor (CSTR) 9
linear equation 4–7 liquid phase reaction 12–13
nonlinear equation 7–13 Cramer’s rule
algebraic manipulation concepts 13 implementation 43–48
algorithm 1–2, 51, 58, 61, 64, 70, 247 implication of 38
Euler algorithms 248 inconsistent equations 50–51
Midpoint algorithm 255 2 × 2 matrix 48–49
NR algorithm 124 Python solution 40, 47
secant algorithm 126 Simulink algebraic constraint block 38–39
Thomas algorithm 283 Simulink MATLAB function 39–40
Trapezoidal algorithm 190 Simulink solution 46–47
analytical method 1–3, 28 three linear equations 37
two linear equations 36
backward Euler method 217–222 cubic equation 130–133
graphical explanation 218
manual solution 218–219 data type 324
Python solution 221–222 definite integral 177, 178
Simulink and MATLAB solution 219–221 approximate value 179, 180
bisection method 3, 127 Boole’s rule 193–194
advantages of 90 mentioned function 178
disadvantage of 90 real-valued function 178
false-position methods 93 rectangular approximation 178
implementation of 90–92 Simpson’s rule 179, 182, 184
Python solution 91, 93 Trapezoidal rule 188
Boole’s rule determinant calculation 40–41
analytical integration value 194 Python solution 41–42
definite integral 193–194 Simulink solution 41
graphical representation 194 differential equations
MATLAB code 195 definition of 279
Python solution 195 for mixing tank 16
Simulink solution 194–195 digital computing process 2
boundary conditions (BCs) 279–281 direct integration 188
boundary value problem 281 direct method 3
initial value problems 281
boundary value problem (BVP) 19–27, 279–280 eigenvalue and eigenvector 144
boundary conditions 281 application of 145, 157–163
finite difference method 282–283, 290–302 ordinary differential equation 150–157
initial value problems 281 Python solution 149
shooting method 302–314 Simulink solution 147
Thomas algorithm 283–290 elimination methods 163–167
bracketing method, roots solution with 88–90 eigenvalue and eigenvector 167–168
bisection method 90–93 Python solution 171
false-position methods 93–97 Simulink solution 168–171
graphical representation of 89 Euler explicit method
Python-generated plot 89 Python solution 216–217
Ridders’ method 97–101 Simulink/MATLAB solution 214–216
Euler method 208
cartesian equation 74 application of 248–250
central finite difference 282 interpretation numerical method 208
353
354 Index
Improved
A streamlined A single point search and
experience for of discovery discovery of
our library for all of our content at both
customers eBook content book and
chapter level