This site delves into the connection between mechanical engineering, physics, and mathematics using numerical methods and computer algebra systems (CAS). It presents straightforward articles that explore both analytical and numerical approaches to solving real-world engineering and scientific problems.
Showing posts with label Numerical Methods. Show all posts
Showing posts with label Numerical Methods. Show all posts
The number of bacteria, \(B\), in a culture
that’s subject to refrigeration can be approximated by the formula:
$$\large B = 300000 \; e^{-0.032 \; t}$$
Where:
\(B\) – number of bacteria
\(t\) – time the culture has been
refrigerated, \(hours\)
Using the given formula, calculates the
number of bacteria in the culture, and display the results after 12, 18, 24, .
. ., 72 hours.
Solution
C++ Code
// Calculating the number of
bacterial Growth in specified Time
// Ref. C++ for Engineers and Scientist, page 170
// Gani, 2025-12-12 #include <iostream> #include <cmath> #include <iomanip> using namespace std;
// function prototype int calcNumBacteria(int
time);
int main()
{ int
const minTime = 12; int
const maxTime = 72; int
const stepTime = 6; cout
<< "\n"; //
Table title cout
<< setw(14) <<
left << "Time (hours)" << setw(18) <<
left << "Number of Bacteria" << endl; //
Calculation for
(int
time =
minTime;
time <=
maxTime;
time +=
stepTime)
{ int
const numBacteria = calcNumBacteria(time); cout
<< setw(8) <<
right << time << setw(18) <<
right << numBacteria << endl;
} return
0;
}
// Given function to calculate the
number of bacteria int calcNumBacteria(int
const time) { const
double A = 300000; // constant const
double n = 0.032; // constant double
const result = A * exp(-n * time); //
Explicitly round the double to the nearest whole number before
// returning the int return
static_cast<int>(round(result));
}
Console Output
Time (hours)Number of Bacteria
12204339
18168643
24139182
30114868
3694801
4278240
4864572
5453292
6043982
6636299
7229958
Feel free to comment for inquiry,
clarification, correction or suggestion for improvement. Drop your email to make
a request to the author.
Disclaimer: The formulas and calculations
presented are for technical reference only. Users must verify accuracy and
ensure compliance with applicable engineering standards, codes, and safety
requirements before practical application.
References
Gary R. Bronson and G.J. Borse. C++ for
Engineers & Scientist. 3rd Ed. Course Technology, Cengage
Learning, Boston, Massachusetts. 2010.
The idea behind the shooting method is to convert the BVP to
the initial-value problem (IVP) as in Equation (5) and (6). The given 2nd-order
ODE requires to be converted to the system of ODEs.
Solving the converted IVP requires providing a guess for the value of \(s\) and solve the system numerically using Runge-Kutta
method to get the value of the solution, \(y_{\beta} = y(b)\), at \(x = b\). If \(y_{\beta} \neq \beta\), adjust the guess, \(s\), so that \(y_{\beta} - \beta = 0\). For the given two
guesses of \(s\), compute the best guess to make \(y_{\beta} - \beta = 0\) by employing
the root-finding algorithm which is the Bisection method for this article.
For our given problem in Equation (3) and
(4), two guesses value for \(s\) will be tried for \(y_2(a)\).
$$s_1 = 0.1 , \quad s_2 = \frac{\pi}{2} \tag{7}$$
Figure 1 is the resulting solution for
the IVP using \(s_1\) and \(s_2\).
Figure 1. Solution to ODE IVP with \(y(a) = \alpha\) , \(s_1\) , and \(s_2\).
As shown in Figure 1, the two guesses, \(s_1\) and \(s_2\), do not
meet the \(y(b) = \beta\) or \(y(2) = 0\) boundary conditions. Finding the value of \(s\) that makes \(y_{\beta} - \beta = 0\) requires defining a Residual function in Equation
8.
$$\phi(s) = y(b; s) - \beta \tag{8}$$
Residual function measures how far the solution with
guesses is from satisfying the boundary condition at \(x = b\). For the given sample
problem, \(\phi(s) = 1 \times 10^{-6}\) will be utilized in the root-finding
algorithm, the Bisection method. Figure 2 is the visualization of the solution
for sample ODE BVP.
Figure 2. Solution to ODE BVP using the
Shooting Method.
The solution \(y(x)\) satisfies the boundary
conditions \(y(a) = \alpha\) and \(y(b) = \beta\). Implementation of the Runge-Kutta
method and the Bisection method is used in our Scilab script. The two guesses, \(s_1\) and \(s_2\), and the Residual function \(\phi(s)\) are used as parameters in the
script.
Scilab Script for Figure 2
// Copyright (C) 2025 - I.S.Comia// Date of creation: Jul 12, 2025// Shooting Method in Solving 2nd-Order ODE BVPclear;clc;clf;
// Bundary Value Problem// y'' = -exp(-x.*y)-sin(y'), y(1) = 0, y(2) = 0// y'' = f(x,y,y'), y(a) = alpha, y(b) = beta// Subroutine// y'' = -exp(-x.*y)-sin(y') in Scilab functionfunctiondydx=ode_system(x, y)// y(1) = y, y(2) = y'dydx=[y(2); -exp(x.*y(1))-sin(y(2))];
endfunction// solving the ODE using IVP with guessed initial slope// using Runge-Kutta Methodfunctionyb=solve_ivp(s, a, b, h)// Initial value for y and y'
x =a:h:b;
n =length(x);
y =zeros(2, n);
y(:, 1)=[0; s]; // y(a) = 0, y'(a) = s (Note: s - slope)// this is Runge-Kuttafor i =1:n-1
k1 =h*ode_system(x(i), y(:, i));
k2 =h*ode_system(x(i)+h/2, y(:, i)+ k1/2);
k3 =h*ode_system(x(i)+h/2, y(:, i)+ k2/2);
k4 =h*ode_system(x(i)+h, y(:, i)+ k3);
y(:, i+1)= y(:, i)+(k1 +2*k2 +2*k3 + k4)/6;
endyb= y(1, $); // return y(b)endfunction// Main Function// Parameters
a =1;
b =2;
alpha =0;
beta=0;
h =0.05;
// Two Initial guesses for s = y'(a) or slopes, s @ x = a
s1 =0.1;
s2 =%pi/2;
tol =1e-6;
// Plot of IVP using s1 and s2
x = a:h:b
x0 = a
y1_0 =[0;s1]
y1 =ode(y1_0,x0,x,ode_system)
y2_0 =[0;s2]
y2 =ode(y2_0,x0,x,ode_system)plot(x, y1(1, :), "g.-", "linewidth",1);
plot(x, y2(1, :), "g.-", "linewidth",1);
// Shooting Method with Bisection Methodwhileabs(s2 - s1)> tol
smid =(s1 + s2)/2;
yb1 =solve_ivp(s1, a, b, h);
ybmid =solve_ivp(smid, a, b, h);
if(yb1 -beta)*(ybmid -beta)<0then
s2 = smid;
else
s1 = smid;
endend// Final solution with best guess
s_final =(s1 + s2)/2;
x = a:h:b;
n =length(x);
y =zeros(2, n);
y(:, 1)=[alpha; s_final];
for i =1:n-1
k1 = h *ode_system(x(i), y(:, i));
k2 = h *ode_system(x(i)+ h/2, y(:, i)+ k1/2);
k3 = h *ode_system(x(i)+ h/2, y(:, i)+ k2/2);
k4 = h *ode_system(x(i)+ h, y(:, i)+ k3);
y(:, i+1)= y(:, i)+(k1 +2*k2 +2*k3 + k4)/6;
end// Visualization of solution to ODE BVP
fig =gcf()
fig.figure_size=[700, 700]plot(x, y(1, :), "b-", "linewidth",3);
plot(x, y(1, :), "ro", "linewidth",4.5);
title("$\text{Shooting Method Solution to ODE BVP}$","fontsize",4.5);
xlabel("$\LARGE x$")ylabel("$\LARGE y(x)$")
note =["$\Large y(x) \; \text{w/ IVPs}$";"$\Large y(x) \; \text{w/ BVP}$";""]legend(note,2,with_box=%F)xgrid(color("grey"),1,7)// Plot annotation
h1 =xstring(1.55,0.725,"https://gani-mech-toolbox.blogspot.com")
h1.font_size=2
eqn1 ="$\frac{d^2 y}{dx^2}+e^{-xy}+\sin\left(\frac{dy}{dx}\right)=0\text{,}\;
The shooting method is an effective
approach for solving second-order boundary value problems (BVPs), particularly
in mechanical, thermal, and structural engineering applications. To apply this
method, the BVP is converted into an initial value problem (IVP) by estimating
the necessary initial conditions. The IVP is then solved, and the results are
compared with the boundary conditions at the opposite end. This process is
repeated, adjusting the initial guesses as needed, until the solution satisfies
the boundary conditions. While this approach involves some trial and error,
linear second-order problems typically require no more than two iterations to
converge.
Feel free to comment for inquiry,
clarification, correction or suggestion for improvement. Drop your email to make
a request to the author.
Disclaimer: The formulas and calculations
presented are for technical reference only. Users must verify the accuracy and
ensure compliance with applicable engineering standards, codes, and safety
requirements before practical application.
References
Gerald, C. and Wheatly, P., Applied Numerical Analysis.
Addison-Wesley Publishing Company, Inc. 1994.
The ODE representing exponential growth is a fundamental
model frequently used in real-world application of predictive modeling,
particularly in demographics, ecology, and urban planning, to forecast future
population sizes based on past trends and other factors.
The population growth is represented by the differential
equation shown in Equation (1). The equation signifies that the rate of
population change is directly proportional to the current population size.
$$\frac{dP}{dt}=r \, P \tag{1}$$
Where:
\(dP/dt\) – rate of change of the population with respect to
time
\(P\) – population size at any given initial time
\(r\) – growth rate, an assumed positive constant that influences population growth
Equation (1) has a general solution as shown in Equation
(2).
The ODE representing the population growth
model has the following limitations if applied in predictive modelling. First,
it predicts unlimited and unrealistic growth over the long period of time,
which is not sustainable in the long run due to factors resulting to limitation
of resources. Second, the growth rate considered constant does not account for
changes in birth and death rates or other environmental factors.
Below is the list of models or techniques
for estimating or describing the population aside from exponential growth.
The Scilab scripts used for calculations implements the Euler method to numerically
approximate the solution of a first-order ordinary differential equation
modeling exponential growth. Euler method requires an ODE and initial condition
in the form of Equation (3).
\(P_{n+1}\) is the solution to the ODE and
can be solved by rearranging the Equation (4) leading to Equation (5).
$$P_{n+1} = P_n + h \; f(t, P) \tag{5}$$
The \(f(t,P)\) requires finding the growth rate, \(r\), for the two
conditions as shown in Equation (6).
$$\large r = \frac{\ln \left( {\frac{P_t}{P_0}} \right)}{t} \tag{6}$$
Philippine Statistics
Authority (PSA) Population Estimates
This article will use the exponential growth model to
predict and estimates the population growth of the Philippines in comparison
with a country’s agency (PSA) estimates. The agency is mandated to conduct
national censuses and surveys including those on population.
Table 1 presents the population projections from the PSA up to the year 2055. These projections will be analyzed alongside the model based on exponential growth.
Figure 1 illustrates the difference between two methods of
estimation. The exponential growth model deviates from the PSA estimates after
25 years. Exponential growth models can accurately predict population trends during the initial growth phase, but their reliability decreases as other factors cause deviations from exponential behavior.
Figure 1. Population Growth Model and PSA Estimates
Below is the Scilab script to produce the
results shown in Figure 1.
Scilab Script
// Copyright (C) 2025 - I.S.Comia// Date of creation: Jul 6, 2025// Predictive Modeling using Exponential Growthclear;clc;
// Subroutine// Population or Exponential Growth Model (1st-Order ODE)functiondPdt=f(t, P)globalr;
dPdt= r *P;
endfunctionfunctionr=growthRate(P_0, P_t, t)// calculate the estimated growth rate// input:// P_0 - quantity at t = 0// P_t - quantity at a given time t// t - time// output:// r - estimated growth rater=log(P_t./P_0)./t;
endfunction// Main function// Problem case scenario// Phil. Statistic Authority (PSA) estimated population from year 2020 to 2050// Primary parameters
actYear =[20202025203020352040204520502055];
// Population in millions
Pop =[109.2027113.8631118.8738123.9636128.8260133.0245136.2989138.6727];
Yrs = actYear -2020; // years covered
t = Yrs(2)-Yrs(1);
globalr;
r =growthRate(Pop(1),Pop(2),t); // growth rate estimate
T_initial = Yrs(1); // initial time
P_initial = Pop(1); // initial population (millions)// Secondary parameters
T_final = Yrs($); // years, final time
dt =1/12; // month, step size,
N = T_final/dt; // number of steps// Euler method solution to IVP ODE// Initial conditions for time and P-value
T(1)= T_initial;
P(1)= P_initial;
// Solutionfor k =1:N
dPdt =f(T(k), P(k));
T(k+1)= T(k)+ dt;
P(k+1)= P(k)+ dPdt * dt;
end// Plotting of ODE solutionclf;
fig =gcf()
fig.figure_size=[700, 700]plot(T,P,"b-","LineWidth",4)title("Population Growth Model, Year 2020~2055","FontSize",4)xlabel("Time (years)","FontSize",3.5)ylabel("Population (millions)","FontSize",3.5)xgrid(7,1)// Population estimate for T_value~5 years or Year 2025
idT =max(find(T <=5.05));
T_value = T(idT);
P_value = P(idT);
mprintf("For T_value: %4.2f, P_value: %6.3f \n", T_value, P_value)// Plot of information for Year 2025plot(T_value,P_value,"rs","MarkerFaceColor","r","MarkerSize",13)
ann_1=xstring(T_value+0.75,P_value-1,["Year:2025,Pop:",string(round(P_value)),"M"])
ann_1.font_size=2
ann_2 =xstring(20,102.5,"https://gani-mech-toolbox.blogspot.com")
ann_2.font_size=2
ann_3 =xstring(T_initial-2.5,P_initial-2.5,"Year: 2020")
ann_3.font_size=2
T_line =[T_value T_value T_initial-5];
P_line =[100 P_value P_value];
plot(T_line,P_line,"r--","LineWidth",1)// PSA population estimateplot(Yrs,Pop,"ko","MarkerFaceColor","k","MarkerSize",8)
ann_4 =["Exponential Growth Model";"Est Pop @ Year 2025";"";"PSA Pop Estimate"]
ann_5 =legend(ann_4,2,with_box=%F)
ann_5.font_size=2
ax =gca()
ax.data_bounds=[-5100; 40150]
Feel free to comment for inquiry,
clarification, correction or suggestion for improvement. Drop your email to make
a request to the author.
Disclaimer: The formulas and calculations
presented are for technical reference only. Users must verify the accuracy and
ensure compliance with applicable engineering standards, codes, and safety
requirements before practical application.