An ordinary differential equation
This page shows a part of a tutorial by SciML (https://tutorials.sciml.ai/html/models/01-classical_physics).
In the tutorial, a simple harmonic oscillator is shown. It is given by
$$\ddot{x} + \omega^2 x = 0$$
with the analytical solution
$$\begin{eqnarray} x(t) &= A \cos (\omega t - \phi) \\ v(t) &= - A \omega \sin (\omega t - \phi) \end{eqnarray}$$
where
$$A = \sqrt{c_1 + c_2} \: \: \: \: \: \text{and} \: \: \: \: \: \tan \phi = \frac{c_2}{c_1}$$
with $c_1$, $c_2$ constants determined by the initial conditions such that $c_1$ is the initial position and $\omega c_2$ is the initial velocity.
Instead of transforming this to a system of ODEs to solve with ODEProblem
, we can use SecondOrderODEProblem
as follows.
using OrdinaryDiffEq, Plots
With parameter:
ω = 1;
and initial conditions:
x₀ = [0.0];
dx₀ = [π / 2];
tspan = (0.0, 2π);
ϕ = atan((dx₀[1] / ω) / x₀[1]);
A = √(x₀[1]^2 + dx₀[1]^2);
We define the problem as follows:
function harmonicoscillator(ddu, du, u, ω, t)
ddu .= -ω^2 * u
end;
And pass it to the solvers:
prob = SecondOrderODEProblem(harmonicoscillator, dx₀, x₀, tspan, ω);
sol = solve(prob, DPRKN6())
timestamp | value1 | value2 | |
---|---|---|---|
1 | 0.0 | 1.5708 | 0.0 |
2 | 0.000636215 | 1.5708 | 0.000999364 |
3 | 0.00699836 | 1.57076 | 0.0109929 |
4 | 0.0377005 | 1.56968 | 0.0592058 |
5 | 0.109108 | 1.56146 | 0.171047 |
6 | 0.223866 | 1.5316 | 0.348718 |
7 | 0.375931 | 1.4611 | 0.5767 |
8 | 0.565637 | 1.32614 | 0.841874 |
9 | 0.797809 | 1.09685 | 1.12442 |
10 | 1.07487 | 0.747455 | 1.38156 |
... |
let
plot(
sol,
vars=[2, 1],
linewidth=2,
title="Simple Harmonic Oscillator",
xaxis="Time",
yaxis="Elongation",
label=["x" "dx"],
)
plot!(t -> A * cos(ω * t - ϕ), lw=3, ls=:dash, label="Analytical Solution x")
plot!(t -> -A * ω * sin(ω * t - ϕ), lw=3, ls=:dash, label="Analytical Solution dx")
end
Built with Julia 1.9.1 and
OrdinaryDiffEq 6.53.1Plots 1.38.16
To run this tutorial locally, download this file and open it with Pluto.jl.