@@ -106,6 +106,60 @@ plot(p,xlims = (-9,9))
106106
107107## Simple Harmonic Oscillator
108108
109+ Another classical example is the harmonic oscillator, given by
110+ $$
111+ \ddot{x} + \omega^2 x = 0
112+ $$
113+ with the known analytical solution
114+ $$
115+ \begin{align*}
116+ x(t) &= A\cos(\omega t - \phi) \\
117+ v(t) &= -A\omega\sin(\omega t - \phi),
118+ \end{align*}
119+ $$
120+ where
121+ $$
122+ A = \sqrt{c_1 + c_2} \qquad\text{and}\qquad \tan \phi = \frac{c_2}{c_1}
123+ $$
124+ with $c_1, c_2$ constants determined by the initial conditions such that
125+ $c_1$ is the initial position and $\omega c_2$ is the initial velocity.
126+
127+ Instead of transforming this to a system of ODEs to solve with `ODEProblem`,
128+ we can use `SecondOrderODEProblem` as follows.
129+
130+ ```julia
131+ # Simple Harmonic Oscillator Problem
132+ using OrdinaryDiffEq, Plots
133+
134+ #Parameters
135+ ω = 1
136+
137+ #Initial Conditions
138+ x₀ = [0.0]
139+ dx₀ = [π/2]
140+ tspan = (0.0, 2π)
141+
142+ ϕ = atan((dx₀[1]/ω)/x₀[1])
143+ A = √(x₀[1]^2 + dx₀[1]^2)
144+
145+ #Define the problem
146+ function harmonicoscillator(ddu,du,u,ω,t)
147+ ddu .= -ω^2 * u
148+ end
149+
150+ #Pass to solvers
151+ prob = SecondOrderODEProblem(harmonicoscillator, dx₀, x₀, tspan, ω)
152+ sol = solve(prob, DPRKN6())
153+
154+ #Plot
155+ plot(sol, vars=[2,1], linewidth=2, title ="Simple Harmonic Oscillator", xaxis = "Time", yaxis = "Elongation", label = ["x" "dx"])
156+ plot!(t->A*cos(ω*t-ϕ), lw=3, ls=:dash, label="Analytical Solution x")
157+ plot!(t->-A*ω*sin(ω*t-ϕ), lw=3, ls=:dash, label="Analytical Solution dx")
158+ ```
159+
160+ Note that the order of the variables (and initial conditions) is `dx`, `x`.
161+ Thus, if we want the first series to be `x`, we have to flip the order with `vars=[2,1]`.
162+
109163### Double Pendulum
110164
111165```julia
0 commit comments