Lesson 9 of 15

Simple Harmonic Motion

Simple Harmonic Motion

A mass on a spring oscillates. The restoring force is proportional to displacement:

F=kxquadRightarrowquadmx=kxF = -k x quad Rightarrow quad m x'' = -k x

Dividing by mass and letting ω2=k/m\omega^2 = k/m:

x=ω2xx'' = -\omega^2 x

Reducing to a System

A second-order ODE like this is converted to a first-order system by introducing velocity v=xv = x':

dxdt=v\frac{dx}{dt} = v dvdt=ω2x\frac{dv}{dt} = -\omega^2 x

State vector: [x,v][x, v]. This is the standard trick — any nth-order ODE becomes a first-order system of nn equations.

Symplectic Euler

For oscillatory problems, the standard Euler method adds energy over time (unstable). The symplectic (semi-implicit) variant updates velocity first, then uses the updated velocity for position:

v = v + h * (-omega**2 * x)   # update v first
x = x + h * v                  # use new v for x

This conserves energy long-term, making it suitable for simulating oscillations.

Exact Solution

x(t)=x0cos(ωt)+v0ωsin(ωt)x(t) = x_0 \cos(\omega t) + \frac{v_0}{\omega} \sin(\omega t)

The motion is sinusoidal with period T=2π/ωT = 2\pi / \omega.

Your Task

Implement harmonic_motion(omega, x0, v0, t_end, n) using the symplectic Euler update. Return (x, v).

Pyodide loading...
Loading...
Click "Run" to execute your code.