Euler's method for modelling the motion of a spherical body in water
Modelling the motion of bodies in fluids is an important part of projects in various fields of science and engineering, including fluid dynamics, oceanography and engineering mechanics.
including fluid dynamics, oceanography, and engineering mechanics. This case study examines the application of Euler's numerical method to modelling the motion of a
of a spherical body in water.
This method allows us to take into account the effects of gravity, the density of the medium and the body, as well as the fluid resistance.
the resistance of the fluid.
To solve the problem, the first-order explicit Euler method is used.
This is one of the simplest methods of numerical integration of ordinary
differential equations (ODEs), which allows us to approximate the solution of the ODE at
at each time step. The basic idea of the method is as follows: the current
value of the function is approximated through its derivative multiplied by a small
time interval.
We set the goal to develop a program in Julia and MATLAB language, which simulates the motion of the
of the body and visualises the results in the form of graphs of changes in diving depth and body velocity over time.
We will also compare the speed of identical scripts in these two languages and analyse syntactic differences.
Then for comparison we will describe the code in MATLAB and Julia in separate functions with
output the results of measuring the time spent on initialisation, calculations in the loop
and output of graphs.
using MATLAB
using Images
function test_MATLAB()
mat"""
tic
rho_w = 1000; % Плотность воды (кг/м^3)
rho = 800; % Плотность тела (кг/м^3)
g = 9.81; % Ускорение свободного падения (м/с^2)
dt = 0.01; % Шаг по времени (с)
T = 5; % Общее время моделирования (с)
% Количество шагов
N = round(T / dt);
% Массивы для хранения результатов
z = 0; % Начальная глубина (м)
v = 0; % Начальная скорость (м/с)
time = 0; % Время
T = toc;
disp("Время инициализации: " + string(T))
tic
% Моделирование
for n = 1:N-1
time(n+1) = dt * n;
z(n+1) = z(n) + v(n) * dt;
v(n+1) = v(n) + g * (rho_w - rho) / rho * dt;
end
T = toc;
disp("Время цикла: " + string(T))
tic
% Построение графиков
figure;
% Глубина от времени
subplot(1, 2, 1);
plot(time, z);
xlabel('Время (с)');
ylabel('Глубина (м)');
grid on;
% Скорость от времени
subplot(1, 2, 2);
plot(time, v);
xlabel('Время (с)');
ylabel('Скорость (м/с)');
grid on;
saveas(gcf, 'mat_plot.png');
T = toc;
disp("Время отображения графиков:" + string(T))
"""
end
using TickTock
function test_Julia()
start_time = time()
rho_w = 1000.0 # Плотность воды (кг/м³)
rho = 800.0 # Плотность тела (кг/м³)
g = 9.81 # Ускорение свободного падения (м/с²)
dt = 0.01 # Шаг по времени (с)
T = 5.0 # Общее время моделирования (с)
N = floor(Int, T / dt) + 1 # Расчёт количества шагов
t = zeros(N) # Время
t[1] = 0.0 # Начальное время
z = zeros(N) # Позиция (глубина)
z[1] = 0.0 # Начальная позиция (м)
v = zeros(N) # Скорость
v[1] = 0.0 # Начальная скорость (м/с)
println("Время инициализации: " * string(time() - start_time))
start_time = time()
# Моделирование движения
for n in 1:N-1
t[n+1] = dt * n
z[n+1] = z[n] + v[n] * dt
v[n+1] = v[n] + g * (rho_w - rho) / rho * dt
end
println("Время цикла: " * string(time() - start_time))
start_time = time()
# Глубина от времени
A = plot(t, z,
xlabel="Время (с)",
ylabel="Глубина (м)")
# Скорость от времени
B = plot(t, v,
xlabel="Время (с)",
ylabel="Скорость (м/с)")
fig = plot(A, B, legend=false)
savefig(fig, "jl_plot.png")
println("Время отображения графиков:" * string(time() - start_time))
end
Let's look at the main differences between these implementations.
- variable types
MATLAB: dynamic typing, types of variables are not explicitly declared.
types of variables are not declared explicitly.
Julia: static typing, it is often required to specify the types of variables to improve performance.
types of variables to improve performance.
- array indexing
MATLAB: starts with one and in parentheses ().
Julia: starts with one but in square brackets [].
- Printing values
MATLAB: function disp is used.
Julia: the println function is used.
- Comments
MATLAB: one-line comments start with %.
Julia: one-line comments start with #.
- Graphs
MATLAB: change functions are broken down into many separate commands.
Julia: all changes to graphs are represented as plot parameters.
Now let's compare the speed and results of the algorithms.
test_MATLAB()
test_Julia()
Judging by the presented results, Julia significantly
surpasses MATLAB on the speed of execution of each
steps of the process. Below is a brief breakdown of each step.
-
Initialisation in Julia is about 120 times faster.
-
The cycle processing time in Julia is about 1300 times shorter.
-
Julia displays graphs about 21 times faster.
# Загружаем изображения
jl_plot = load("$(@__DIR__)/jl_plot.png")
mat_plot = load("$(@__DIR__)/mat_plot.png")
# Объединяем изображения
print("jl_plot, mat_plot")
hcat(jl_plot, imresize(mat_plot, size(jl_plot)))
It can be seen that the graphs in both languages are of the same type. The same applies to the accuracy of the calculations.
Conclusion
Syntax of languages is a matter of taste, a matter of purely subjective evaluation.
But the speed can be measured and evaluated objectively. And it turns out that Julia is much faster at all the key stages of code execution.
key stages of code execution - from initialisation
to plotting. These advantages may be
can be attributed to stricter static typing,
JIT compilation, and careful optimisation of the language.
MATLAB, while still a powerful tool for scientific
calculations, it is inferior to Julia in terms of speed, especially
when it comes to high-level computational tasks,
where performance is critical.