Showing posts with label Physics. Show all posts
Showing posts with label Physics. Show all posts

Saturday, 25 January 2025

Simple Harmonic Motion Solution using Runge-Kutta RK4 Method

Topic: Oscillatory Motion and Numerical Solution of ODE

Subject: Physics and Numerical Methods

Tool: Scilab

By: Gani Comia, Jan. 2025

The 4th -order Runge-Kutta methods (RK4) is also used for numerical technique of approximating solution to the initial value problem (IVP) of 2nd- order ordinary differential equation (ODE). This article presents the solution to the basic equation of simple harmonic motion (SHM) using RK4 algorithm in Scilab.

SHM is a form of nonhomogeneous linear differential equation (LDE) of second-order as shown in Equation (1).

$$y''\;+\;p(t)\,y'\;+\;q(t)\,y\;=\;r(t) \tag{1}$$ 

In order to solve a given higher-order differential equation, it is required to be converted to a system of first-order differential equations as presented below.

Let us define the following dependent variables, \(y_1\) and \(y_2\):

$$y_1\;=\;y \tag{2}$$

$$y_2\;=\;y' \tag{3}$$

Then, the nonhomogeneous LDE can be re-written as a system of 1st-order ODE in Equation (4) and (5):

$$y'_1\;=\;y_2 \tag{4}$$

$$y'_2\;=\;-p(t)\,y_2\;-\;q(t)\,y_1\;+\;r(t) \tag{5}$$

With that presented, let us define and illustrate a problem using the basic equation of SHM and convert its 2nd-order ODE to a system of 1st-order to use the RK4 method in finding its approximate solution.

Figure 1. Single-Degree of Freedom (SDOF) Spring-Mass Model Oscillation Problem

The SDOF spring-mass model oscillation can be described by the basic equation of SHM shown in Equation (6).

$$m\,\frac{d^2y}{dt^2}\,+\,k\,y\,=\,0, \quad y(t_0)=y_0\;\;\text{and}\;\;y'(t_0)=y'_0 \tag{6}$$

Where:

\(m\) – mass
\(k\) – spring constant
\(t\) – time
\(t_0\) - initial time
\(y_0\) – initial displacement
\(y’_0\) – initial velocity

The solution to the ODE of SHM can be approximated using the Runge-Kutta (RK4) Method. The RK4 will be using the same algorithm presented in the previous article “First-Order IVP ODE Solution using Runge-Kutta RK4 Method” with the link shown: https://gani-mech-toolbox.blogspot.com/2025/01/first-order-ivp-ode-solution-using.html. Figure 2 shows the solution to the problem illustrated in Figure 1.

Figure 2. Solution to Spring-Mass Model System with RK4 using Scilab Script

The Scilab script to solve the given problem is presented below. Each block of the code is commented comprehensively for better understanding of the program sequence by the reader.

Scilab Script:

clear;clc;
// single-degree of freedom spring-mass model oscillator system
// m*y'' + k*y = 0  or  y'' + (k/m)*y = 0
// nonhomogeneous linear differential equation (LDE) of second-order
// y'' + p(t)y' + q(t)y = g(t) 
// where: p(t)=0; q(t)=k/m; g(t)=0

// (1) 2nd-order LDE re-written in the system of 1st-order ODEs
function dydt=f(t, y)
    m = 1;                  // kg, mass of the object
    k = 20;                 // N/m, spring constant
    p = 0;                  // coefficient of y'
    q = k/m;                // coefficient of y
    g = 0;                  // forcing function
    dydt = [y(2); -p*y(2) - q*y(1) + g];
endfunction

As you may compare the \(rk4\) function in block (2) to the previous article, the final time, \(t_f\), is used as one of the input arguments instead of the number of intervals, \(n\). Both \(rk4\) functions can be used to come up with the same solution.

// (2) RK4 function or algorithm for 1st-order ODEs
function [t, y]=rk4(f, t0, y0, h, tf)
    n = round((tf - t0)./h);
    t(1) = t0;          // initial time, t0
    y(:, 1) = y0;       // y(t0)=y0 & y'(t0)=y0' in column vector

    for i = 1:n
        // approximate values of slopes of solution curves
        k1 = h * f(t(i), y(:, i));
        k2 = h * f(t(i) + h / 2, y(:, i) + k1 / 2);
        k3 = h * f(t(i) + h / 2, y(:, i) + k2 / 2);
        k4 = h * f(t(i) + h, y(:, i) + k3);
        // estimates of numerical solution
        y(:, i + 1) = y(:, i) + (k1 + 2 * k2 + 2 * k3 + k4) / 6;
        t(i+1) = t(i) + h;
    end
endfunction

// (3) initial conditions and parameters
t0 = 0;             // sec, initial time
tf = 5;             // sec, final time
h = 0.01;           // sec, time step size
y0 = [0.05; 0];     // initial disp & velocity: y(0)=0.05, y'(0)=0

// (4) solution to the ODE by calling RK4 defined function
[t, y] = rk4(f, t0, y0, h, tf);

// (5) solution plot
clf;
plot(t, y(1, :),"b-","linewidth",4);       // displacement plot
plot(t, y(2, :),"r--","linewidth",1.8);    // velocity plot
xlabel("$\Large t \quad \text{(time)}$");
ylabel("$\Large y(t)\;\;\text{or}\;\;\frac{dy(t)}{dt}$");
note1 = "Spring-Mass Model System using Runge-Kutta RK4";
title(note1,"fontsize",3.5);
note2 = ["$\Large y(t)$","$\Large \frac{dy(t)}{dy}$"];
legend(note2, with_box = %F);
note3 = "https://gani-mech-toolbox.blogspot.com"
xstring(0.1,0.35,note3);
xgrid(3,1);

// (6) other plot information
disp(max(y(1,:)), min(y(1,:)))
disp(max(y(2,:)), min(y(2,:)))
ax = gca();
ax.data_bounds = [0 -0.4; 5 0.4];

// (7) natural frequency
format(5);
k = 20;                     // N/m, spring constant
m = 1;                      // kg, mass of object
omega = sqrt(k/m);          // Hz, natural frequency
disp(omega);
note4 = ["$\LARGE\mathbf{\omega_n}\;=\;\text{4.5 Hz}$"];
xstring(0.1,0.25,note4)

The Scilab script in this article can be one of your references to solve any engineering problems that can be described by the nonhomogeneous linear differential equation (LDE) of second-order.

Feel free to comment for inquiry, clarification, or suggestion for improvement. Drop your email to request the soft copy of the file.

Saturday, 4 January 2025

Free-Falling Body under Gravitational Field

Topic: Gravitational Interaction

Subject: Physics

Tool: Scilab

by:  Gani Comia, Jan. 2025

A free-falling body or object falls to the ground under the sole influence of gravity. Air resistance or any form of propulsion that acted on the object are not considered in this concept. The ordinary differential equation (ODE) in equation (1) helps explain the motion of objects in a gravitational field. The acceleration due to gravity, denoted by “\(g\)”, is approximately equal to \(\text{9.8}\;m/s^2\) on the surface of the Earth.

$$\frac{d^2 y}{dt^2}\;=\;-\;g \tag{1}$$

Solution to the given 2nd-order ODE will be based on the initial conditions as shown in equation (2).

$$\left(\;t_0 = t,\;y_0 = y,\;\frac{dy}{dt}(t_0) = v \right) \tag{2}$$

The 2nd-order ODE needs to be transformed in the system of 1st-order ODE before using it to the Scilab’s \(ode()\) function. Figure 1 which shows the position and velocity over time domain is the solution to the ODE. Instantaneous position and velocity at t = 60 sec are plotted on the graph as an example.

Figure 1. Solution to 2nd – order ODE representing Free-Falling Body.

Scilab's Script:

The first block on the script is the re-written 2nd-order ODE in the system of 1st-order ODE’s.

clear;clc;
// y'' = -g                 2nd-order ODE model for free-falling body
// y(0) = 0                 initial position
// y'(0) = 0                initial velocity

// (1) system of 1st-order ODEs equivalent to 2nd-order ODE
function dydt=freeFall(t, y)
    g = 9.8;                // m/s^2, gravitational acceleration
    dydt(1) = y(2);         // dy/dt = v
    dydt(2) = -g;           // dv/dt = -g
endfunction

Time domain considered for this solution is from 0 to 120 seconds and the initial conditions are shown in equation (3).

$$\left(\;t_0 = 0,\;y_0 = 0,\;\frac{dy}{dt}(0) = 0 \right) \tag{3}$$

Its Scilab script is shown below.

// (2) time domain and initial conditions
t = 0:0.1:120;              // sec, time span
t0 = 0;                     // sec, initial time
y0 = [0; 0];                // initial position and velocity

Scilab’s \(ode()\) function is written on below script for the solution.

// (3) solution to ode
y = ode(y0, t0, t, freeFall)

The succeeding scripts are for Scilab plotting and calculation of the instantaneous position and velocity using interpolation. Solution vectors representing position and velocity are given in the variables \(y(1,:)\) and \(y(2,:)\) respectively. The function \(interp1()\) is used for interpolation at t = 60 sec.

// (4) plot size
clf;
f=gcf();
f.figure_size=[600,700];

// (5) time and displacement plot
subplot(2,1,1)
plot(t,y(1,:),"b-","linewidth",3)
title("$\large\text{Displacement, Free-Falling Body}$")
ylabel("Displacement [m]","fontsize",3)
legend(["$\LARGE {y}$"],with_box = %F)
xgrid(3,1)

// (6) time and velocity plot
subplot(2,1,2)
plot(t,y(2,:),"r-","linewidth",3)
title("$\large\text{Velocity, Free-Falling Body}$")
xlabel("Time [sec]","fontsize",3)
ylabel("Velocity [m/sec]","fontsize",3)
legend(["$\LARGE\frac{dy}{dt}$"],with_box = %F)
xgrid(3,1)
xstring(70,-400,["https://gani-mech-toolbox.blogspot.com"])

// (7) interpolating position, Yx, and its velocity, Vx
format(8)
tx = 60;                            // sec, sample time
Yx = interp1(t, y(1,:), tx);        // m, distance
Vx = interp1(t, y(2,:), tx);        // m/s^2, velocity
disp(tx, Yx, Vx)

// (8) plot of interpolated data, time and position
subplot(2,1,1)
vertLnXs = [tx tx]; vertLnYs = [0 Yx];
horLnXs = [0 tx]; horLnYs = [Yx Yx];
plot(vertLnXs, vertLnYs,"m--","linewidth",1.25)
plot(horLnXs, horLnYs,"m--","linewidth",1.25)
plot(tx,Yx,"mo")
xstring(tx+1,Yx,["y = "+string(Yx)+" m @ 60 sec"])
a = gca();
a.children.children.mark_background = 1;

// (9) plot of interpolated data, time and velocity
subplot(2,1,2)
vertLnXs = [tx tx]; vertLnYs = [0 Vx];
horLnXs = [0 tx]; horLnYs = [Vx Vx];
plot(vertLnXs, vertLnYs,"m--","linewidth",1.25)
plot(horLnXs, horLnYs,"m--","linewidth",1.25)
plot(tx,Vx,"mo")
xstring(tx+1,Vx,["dy/dt = "+string(Vx)+" m/sec @ 60 sec"])
a = gca();
a.children.children.mark_background = 1;
For the next article, introduction of air resistance to the ODE representing the free-falling body will be presented.

Feel free to comment for inquiry, clarification, or suggestion for improvement. Drop your email to request the soft copy of the file.

Friday, 3 January 2025

Half-Life Calculation of Radioactive Nuclei

Topic: Radioactive Decay

Subject: Physics

Tool: Scilab

By: Gani Comia, Jan. 2025

Half-life of the radioactive substance is defined as the time it takes for half of the radioactive nuclei in a sample to decay. This can be calculated from the initial value condition (IVC) of the ordinary differential equation (ODE) that describes radioactive decay as shown in Equation (1).

$$\frac{dN}{dt}\;=\;-\lambda\;N \tag{1}$$

Where:

\(N\) - amount of radioactive nuclei at time \(t\),
\(\lambda\) - decay constant of a nuclei in per unit time,

And the initial conditions are,

$$\left(\;t_0 = 0 \;,\; N_0 = 1 \right) \tag{2}$$

This article will present the calculation of the half-life and plot the decay profile of the sample nuclei \(^{226}Ra_{88}\) for illustration of the solution to ODE as shown in Figure (1) using Scilab scripting.

Figure 1. Radioactive Decay and Half-Life of \(^{226}Ra_{88}\).

Scilab Script:

The solution will be based on the IVC of the ODE representing radioactive decay. Its ODE from Equation (1) can be written in Scilab script.

clear;clc;
// ordinary differential equation with initial value condition
// dN/dt = f(t,N) with IVC N(0)=1.

// (1) differential equation for radioactive decay
function dNdt=f(t, N)
    // lambda - per year, decay constant of radioactive substance
    lambda = (1.4e-11)*(60*60*24*365); // for 226 Ra_88 
    dNdt = -lambda.*N;
endfunction

Assume an initial amount of nuclei as \(N_0 = 1\) at the initial time, \(t_0 = 0\). If the amount of radioactive nuclei reached \(N_h = 0.5\), which is \(\frac{1}{2}\) of the initial condition, then that is the time the given amount reached its half-life. Our simulation will be run from 0 to 5000 years, as we still do not know the exact time of its half-life. Here is the code snippet for the initial condition and time domain.

// (2) initial condition and time domain
t0 = 0;
N0 = 1;     // unit, arbitrary amount, 
            // if N = 0.5, it reaches the substance's half-life
t = 0:5000; // years, time domain

Scilab has a built-in function, \(ode()\), to provide a solution to first-order IVC for ODEs.

// (3) ODE solution using the Scilab ode() function
N = ode(N0,t0,t,f);

Plotting of the solution for the amount of nuclei, \(N\), for the given time domain can be done using the below script.

// (4) plotting of solution
clf;
plot(t, N,"b-","linewidth",3)
title("$\large\text{Radioactive Decay of}\;{Ra_{88}^{226}}$")
xlabel("Time [ years ]","fontsize",3)
ylabel("Amount of Nuclei [ unit ]","fontsize",3)
legend("$\LARGE\frac{dN}{dt}\;=\;-\,\lambda\,N$",with_box = %F)
xstring(3000,0.8,"https://gani-mech-toolbox.blogspot.com")
xgrid(3,1)

Solving for the half-life, Th, for the given amount, Nh = 0.5, can be done with the use of the Scilab interpolation function, interp1().

// (5) interpolation to find the half-life, Th, for Nh = 0.5 unit
Nh = 0.5;
Th = interp1(N,t,Nh);
disp(Th)

The information about the half-life will be plotted using the following script. 

// (6) plotting of half-life lines
verX = [Th Th];
verY = [0 Nh];
plot(verX, verY, "r--","linewidth",1.5)
horX = [0 Th];
horY = [Nh Nh];
plot(horX, horY, "r--","linewidth",1.5)
plot(Th,Nh,"ro");

format(7);
note1 = ["T (yrs) = "+string(Th)+"; N (unit) = "+string(Nh)];
note2 = ["$\Large \textbf{Half - Life}$"];
xstring(Th,Nh,note1)
xstring(Th,Nh+0.05,note2)
a = gca();
a.children.children.mark_background = 5;

The Scilab script provided here can be used for other substances with different decay constants to calculate the half-life and decay profile.

Feel free to comment for inquiry, clarification, or suggestion for improvement. Drop your email to request the soft copy of the script file.

Wednesday, 1 January 2025

Newton’s Law of Cooling with Euler’s Method Solution to IVP ODE

Topic: Newton’s Law of Cooling and Euler’s Method to IVP ODE

Subject: Physics and Numerical Methods

Tool: Scilab

By: Gani Comia, Jan. 2025

This article presents a solution as to how long it will take for an object to cool down to a specified temperature and thereby to ambient temperature. The object is being taken out of the oven at \(230^\circ C\) and put in place where the ambient temperature is \(30^\circ C\). Neglecting the heat transfer due to conduction where the object is in contact with, the time to cool it down to a particular temperature due to natural convection and radiation can be estimated using the ordinary differential equation (ODE) representing the Newton’s Law of Cooling shown in Equation (1).

$$\frac{dT}{dt}\;=\;-k \left(T(t) - T_{env} \right) \tag{1}$$

Where:

\(T(t)\) - object temperature at time \(t\),
\(T_{env}\) - environment temperature,
\(k\) - cooling constant, 
\(dT/dt\) - rate of change of temperature with time,

The analytical solution to the ODE representing Newton’s law of cooling can be found by integrating both sides of the equation as shown in Equation (2).

$$\int_{T_{0}}^{T_{t}} dT\;=\;-k \int_{0}^{t} \left(T(t)-T_{env} \right) dt \tag{2}$$

For this article, a numerical solution using the Euler method of approximating the solution of a first-order differential equation is presented with the use of Scilab. Euler methods require an ODE to be in the form of Equation (3).

$$\frac{dT}{dt}\;=\;f\left(t,T\right) \tag{3}$$

With the given initial condition,

$$\left(t_{0},\;T_{0}\right) \tag{4}$$

The approximate solution using Euler's method is shown in Equation (5).

$$\frac{\Delta T}{\Delta t}\; \approx \; \frac{T_{n+1}-T_{n}}{h}\; \approx \; f\left(t,T \right) \tag{5}$$

Or by rearranging and solving for \(T_{n+1}\),

$$T_{n+1}\;=\;T_{n}+h \;f\left(t,T\right) \tag{6}$$

The \( f(t,T)\) requires finding the cooling constant, \(k\), for a specific material. If this property seems to be unavailable or difficult to find, experimental data can be used as the basis for calculating the \(k\) using Equation (7).

$$k\;=\;- \frac{1}{t} \ln \left[ \frac{T(t) - T_{env}}{T_{0} - T_{env}} \right] \tag{7}$$

Figure (1) is the illustration of the condition to be given a solution using Newton’s law of cooling by applying Euler's method of solving ODE.



Figure 1. An object at \(230^\circ C\) exposed in an environment at \(30^\circ C\).

To provide a simulation of the given condition in Figure (1), experimental data were gathered to calculate the cooling constant, \(k\), from the given temperature and time. The cooling constant, \(k = 0.08 \;\text{per min}\), was calculated from the given parameters and Scilab script.

// Copyright (C) 2024 - Gani Comia
// Experimental Cooling Constant
clear;clc;

// (1) defining cooling constant function
function k=f(t, Tt, T0, Tenv)
    // where:
    // t - min, time consideration
    // Tt - deg C, temperature at time t
    // T0 - deg C, initial temperature
    // Tenv - deg C, environment temperature
    k = -(1/t).*log((Tt - Tenv)./(T0 - Tenv));
endfunction

// (2) experimental data
t = 30;                     // min, time between T0 and Tt
T0 = 230;                   // deg C, initial temp
Tt = 50;                    // deg C, temp at time t
Tenv = 30;                  // deg C, ambient temp

// (3) cooling constant calculation
k = f(t,Tt,T0,Tenv)
mprintf("Cooling Constant, k = %4.2f per min\n", k)
Having this cooling constant, a simulation of Newton’s law of cooling can be performed. The codes provided in the simulation should be saved on a different file from the script used for estimating the cooling constant.

The first block of the script defines the physical parameter under consideration.

clear;clc;

// (1) physical parameters
T0 = 230;                   // deg C, initial temp of the object
Tenv = 30;                  // deg C, ambient temp
k = 0.08;                   // per min, experimental cooling constant
dt = 0.05;                  // min, time step
totalTime = 80;             // min, total simulation time

The time domain in the simulation is divided into smaller step sizes for accuracy of solution. Initial time and temperature are given on the next block of script.

// (2) initial conditions and derived parameters
time = 0:dt:totalTime;
nSteps = length(time);
T = zeros(nSteps, 1);
T(1) = T0;

Equation (6), which is the numerical solution to the ODE using the Euler method, is transformed in the Scilab script. It uses the \(for-loop\) function to obtain the solution over the desired range.

// (3) numerical solution to ODE using Euler Method
for i = 1:nSteps-1
    dTdt = -k * (T(i) - Tenv);  // deg C/min, rate of temp change
    T(i+1) = T(i) + dTdt * dt;  // deg C, temp at the next time step
end

The Scilab \(plot()\) function is used to visualize the solution from the Euler method of approximation. Finding the temperature for a given time can be estimated using interpolation by the use of the \(interp1()\) function.

// (4) graph for visualization of solution
clf;
plot(time, T, "b","linewidth",2.5);
xlabel("Time, t [ min ]","fontsize",2);
ylabel("Temperature, T [ °C ]","fontsize",2);
title("Newton''s Law of Cooling Simulation","fontsize",3);
note = ["T0="+string(T0)+"°C, Tenv="+string(Tenv)+"°C, k="+string(k)]
legend(note,with_box = %F);
xgrid(3,1);

// (5) interpolating temp, Tx, for the particular time, tx
format(6)
tx = 17.5;                      // min, sample time
Tx = interp1(time, T, tx);      // deg C, interpolated temp
disp(tx, Tx)

// (6) plotting lines for tx and Tx
xptVer = [tx tx];
yptVer = [0 Tx];
plot(xptVer, yptVer, "r--","linewidth",1.5)
xptHor = [0 tx];
yptHor = [Tx Tx];
plot(xptHor, yptHor, "r--","linewidth",1.5)
plot(tx,Tx,"ro");
note1 = ["t (min) ="+string(tx)+"; T (°C) ="+string(Tx)];
xstring(tx,Tx,note1);
xstring(45,200,["https://gani-mech-toolbox.blogspot.com"])
eqn1=["$\LARGE\frac{dT}{dt}\;=\;{-k}\left(T-T_\mathbf{{env}}\right)$"];
xstring(45,166,eqn1);
a = gca();
a.children.children.mark_background = 9; 
Figure 2 is the solution over the range of time.


Figure 2. Plot of the Solution to Newton’s Law of Cooling using Euler’s Method.


This Scilab toolbox is a powerful tool for visualizing solution data and calculating specific conditions.

Feel free to comment for inquiry, clarification, or suggestion for improvement. Drop your email to request the soft copy of the file.

C++ and Python for Numerical Solution to Spring-Mass-Damper Model

Topic: SDOF Spring-Mass-Damper System Subject: Numerical Methods & Mechanical Vibration Tools: C++, CodeBlocks, GitHub Copilot, LabP...