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.

Tuesday, 31 December 2024

Laplace Equation 1D for Steady-State Heat Conduction Model in BVP PDE

Topic: Steady-State Heat Conduction

Subject: Heat Transfer and Numerical Methods

Tool: Scilab

By: Gani Comia, Jan. 2025

The steady-state heat conduction model, as represented by the Laplace equation in one dimension (1D), is the simplest partial differential equation (PDE) you may encounter solving. This equation explains the temperature characteristics or profile between the boundaries of the given domain. Presented in this article is the application of the Laplace equation in 1D using the Finite Difference Method (FDM) for the solution.

The Laplace equation in 1D for the steady-state heat conduction is shown in Equation (1).

$$\frac{\partial^2 u}{\partial x^2}\;=\;0 \tag{1}$$

The second-order PDE in 1D can also be written in ordinary differential equations (ODE). This can be approximated using the FDM shown in Equation (2).

$$\frac{d^2 u}{d x^2}\; \approx \; \frac{u_{i+1} - 2 u_i + u_{i-1}}{\left(\Delta x\right)^2}\;=\;0 \tag{2}$$

This leads to the solution in Equation (3),

$$u_i\;=\; \frac{u_{i+1} + u_{i-1}}{2} \quad for \quad i\;=\;2,3, \ldots ,N-1 \tag{3}$$

With boundary conditions,

$$u_1\;=\;u_1, \quad u_N\;=\;u_L \tag{4}$$

Let us illustrate an example of steady-state heat conduction as shown in Figure (1) and apply the FDM solution to understand its temperature profile between boundaries. The Scilab script to implement the solution will be explained in detail in relation to the Laplace equation in 1D.

Figure 1. Sample Domain under Steady-State Heat Conduction

The solution using the Scilab script is shown below. A short explanation is provided for each code snippet.

Scilab Script.

clear;clc;clf;

// (1) primary & derived parameters
L = 100;                            // mm, length of workpiece
Nx = 11;                            // unit, number of nodes
dx = L / (Nx - 1);                  // mm, spatial step

Equation (5) is the boundary condition for this problem.

$$u_1\;=\;u_1, \quad u_{2,3, \dots ,N-1,N}\;=\;u_L \tag{5}$$

// (2) boundary temperature conditions
u = zeros(Nx, 1) + 25;              // node temp cond @ 25 deg C
u(1) = 100;                         // boundary temperature

The temperature condition at node points between boundaries can be solved using the "for-end” function of the Scilab.

// (3) temperature profile at node points using FDM
for i = 2:Nx-1
    u(i) = (u(i+1) + u(i-1))/2;
end

Below is the script for plotting the temperature profile.

// (4) plotting of temperature at node points
f = gcf()
f.figure_size = [600,600]

len = linspace(0,L,Nx);
plot(len, u, 'r-o');
title("Temperature Profile @ Eleven (11) Node Points","fontsize",3)
xlabel("Length, x [ mm ]","fontsize",3)
ylabel("Temperature, T [ C ]","fontsize",3)
xstring(58,73,"https://gani-mech-toolbox.blogspot.com")
eqn = ["$\LARGE \;\frac{\partial^2\,T}{\partial x^2}\,=\,0$"]
legend(eqn,with_box=%f)
xgrid(3,1)

a = gca()
a.data_bounds = [0 0; L max(u)]
a.children.children.mark_background = 9;

Figure (2) is the resulting plot from executing the whole script.


Figure 2. Graphical Solution for Laplace 1D using FDM with 11 Node Points

The given boundary conditions in Equation (5) will result in a curved-like temperature profile. If Equation (4) is considered as boundary conditions with the corresponding change in primary and derived parameters, specifically reducing the number of node points to 3, a linear temperature profile will become the solution.

Below is the modified script for 3 node points.

// (1) primary & derived parameters
L = 100;                            // mm, length of workpiece
Nx = 3;                             // unit, number of nodes
dx = L / (Nx - 1);                  // mm, spatial step

Figures (3) and (4) are the illustration and graphical solution for 3 node points leading to a linear temperature profile.

Figure 3. Sample Domain with 3 Node Points under Steady-State Heat Conduction


Figure 4. Graphical Solution to Laplace 1D using FDM for 3 Node Points

The number of node points taken into consideration in solving the Laplace equation using FDM dictates the type of temperature profile, linear or curve-like. You may send a comment about the consideration for a basis as to how many node points are to be used for certain conditions of the steady-state heat conduction model.

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

Monday, 23 December 2024

Transient Heat Conduction using Explicit FDM Solution to Thermal Diffusion

Topic: Transient Heat Conduction & Thermal Diffusion

Subject: Heat Transfer

Tool: Scilab

By: Gani Comia, Dec. 2024

This article presents the solution to the transient heat conduction system represented by the thermal diffusion equation in one dimension shown in equation (1).

$$\frac{\partial u}{\partial t}\;=\;D\;\frac{\partial^2 u}{\partial x^2} \tag{1}$$

The diffusion equation can be solved with the explicit finite difference method (FDM) given by the equation (2).

$$u_{i}^{n+1}\;=\;u_{i}^{n}\;+\;\alpha\left(u_{i+1}^{n}\,-\,2 u_{i}^{n}\,+\,u_{i-1}^{n}\right) \tag{2}$$

In solving the explicit FDM, equation (3) which is defined as a stability factor, must be satisfied to maintain numerical stability:

$$\alpha\;\leq\frac{1}{2} \tag{3}$$

or:

$$\frac{D\,\Delta t}{\left(\Delta x\right)^2}\,\leq\,\frac{1}{2}\tag{4}$$

One may refer to the detailed discussion and derivation of numerical methods of its solution. Here we are going to present the application of solving a thermal diffusion problem in one dimension using FDM. The thermal diffusion equation governs transient heat conduction where the temperature within the material changes over time and space.

Consider an example material shown in Figure 1; the temperature at each finite or nodal point at a particular time as represented by \(T(x,t)\) can be solved by using the explicit FDM.

Figure 1. Sample Material Block with Initial and Boundary Temperature. 

Figure 2 is the solution for the illustrated problem. Shown is the temperature profile, \(T(x,t)\), for a particular period of time. For example, at t = 1 sec, the material had the initial temperature of 30 deg C, and as the time progressed, the temperature at each node point became equal to the boundary temperature. The thermal diffusion equation solves for the time the material temperature reaches the boundary condition from the initial state.

Figure 2. Graphical Plot of the Explicit FDM Solution.

Scilab is used to simulate the solution with the use of FDM. An explanation of each chunk of the program script is provided here for more clarity. First on the script are parameters that defined the physical properties of the problem.

// (1) parameters
L = 160;                        // mm, length of workpiece
Nx = 40;                        // unit, number of spatial points
Time = 1000;                    // sec, time consideration
D = 12;                         // mm^2/s thermal diffusivity of 4340

Derived parameters are secondary variables calculated for explicit FDM.

// (2) derived parameters
dx = L / (Nx - 1);              // mm, spatial step
alpha = 0.5;                    // stability factor
dt = alpha .* dx.^2 ./ D;       // sec, time step for stability factor

Initial and boundary temperature conditions are provided as row vectors of the size of spatial points.

// (3) initial and boundary conditions
u = zeros(Nx, 1) + 30;          // initial temperature @ 30 deg C
u(1) = 200;                     // left boundary temperature
u(Nx) = 200;                    // right boundary temperature

Temperature distributions at each time step are calculated using the for loops of the program. The plot functions are used for the visualization of the results.

// (4) temperature distribution for time steps
for n = 1:Time
    uNew = u;                   // current state of temperature
    for i = 2:Nx-1
        uNew(i) = u(i) + alpha * (u(i+1) - 2*u(i) + u(i-1));
    end
    u = uNew;                   // updated state of temperature
    
    // (5) plotting of space, time & temperature
    f = gcf()
    f.figure_size = [600,700]
    
     function plotFunc(n)
        plot(linspace(0, L, Nx), u, 'b-o');
        title("Temperature Profile @ Time = "+ string(n) + " sec")
        ylabel("Temp [ C ]")
        xgrid(1)
        a = gca()
        a.data_bounds = [0 0; L max(u)]
        a.children.children.mark_background = 9;
    endfunction
        
    select n
        case 1 then                     // @ time = 1 sec
            subplot(3,1,1)
            plotFunc(n)
        case round(Time/5) then         // @ time = 200 sec
            subplot(3,1,2)
            plotFunc(n)
        case Time then                  // @ time = 1000 sec
            subplot(3,1,3)
            plotFunc(n)
            xlabel("Length [ mm ]")
            note1 = ["https://gani-mech-toolbox.blogspot.com"]
            xstring(85,58,note1)
    end
end

Transient heat conduction is the process where the material temperature changes for a short period of time until it reaches the steady-state heat conduction, which depends on the temperature difference between boundaries.

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...