k = 100
100
m = 1
1
ω = sqrt(k/m)
10.0
# Simple Harmonic Oscillator Problem
import OrdinaryDiffEq as ODE, Plots

#Initial Conditions
x0 = 0
0
v0 = 2
2
tspan = (0, 4*pi/ω)
(0, 1.2566370614359172)
A = x0
0
B = v0/ω

#Define the problem
0.2
function harmonicoscillator(ddu, du, u, ω, t)
    ddu .= -ω^2 * u
end

#Pass to solvers
harmonicoscillator (generic function with 1 method)
prob = ODE.SecondOrderODEProblem(harmonicoscillator, 
                                 [v0], 
                                 [x0], 
                                 tspan, 
                                 ω)
�[38;2;86;182;194mODEProblem�[0m with uType �[38;2;86;182;194mRecursiveArrayTools.ArrayPartition{Int64, Tuple{Vector{Int64}, Vector{Int64}}}�[0m and tType �[38;2;86;182;194mFloat64�[0m. In-place: �[38;2;86;182;194mtrue�[0m
timespan: (0.0, 1.2566370614359172)
u0: ([2], [0])
sol = ODE.solve(prob, ODE.DPRKN6())
timestampvalue1value2
10.02.00.0
20.000499751.999980.000999496
30.003364871.998870.00672848
40.01030951.989380.0205824
50.02163271.953380.0429287
60.03672911.866610.0718177
70.05554941.699280.105473
80.07861991.413080.141535
90.106160.9749550.174627
100.138670.3661240.19662
...
t = sol.t  # extracting time from solution
31-element Vector{Float64}:
 0.0
 0.0004997501249375313
 0.00336487244651807
 0.010309471834588583
 0.02163266731231664
 0.03672910309780761
 0.0555494478947054
 ⋮
 0.9648505252275339
 1.0166043914224208
 1.0730274208898432
 1.1322722494744484
 1.2013597923291945
 1.2566370614359172
sin.(t)
#Plot
31-element Vector{Float64}:
 0.0
 0.0004997501041354171
 0.0033648660968017747
 0.010309289211496783
 0.021630980103633787
 0.03672084556276043
 0.055520883765826645
 ⋮
 0.8219637937686642
 0.850325966986029
 0.8786500202851768
 0.905379331276634
 0.9325309554239456
 0.9510565162951535
Plots.plot(sol, idxs = [2, 1], 
           linewidth = 1,
           marker = 'o',
           title = "Simple Harmonic Oscillator",
           xaxis = "Time", 
           yaxis = "Elongation", 
           label = ["x" "v"])
Plots.plot!(t, A * cos.(ω * t) + B * sin.(ω * t), 
            lw = 3, 
            ls = :dash, 
            label = "Analytical Solution x")
Plots.plot!(t, ω * (-A * sin.(ω * t) + B * cos.(ω * t)), 
            lw = 3, 
            ls = :dash, 
            label = "Analytical Solution v")

Built with Julia 1.12.4 and

OrdinaryDiffEq 6.90.1
Plots 1.40.20