An introduction to university physics for Fidello.
Double pendulum animation.
In this article, I explain to Fidello from Foci's Discord server some prerequisite knowledge he needs to effectively derive the equations of motion for a double rigid pendulum and then cover more advanced topics for him. In theory, the derivation of the equations of motion for a double rigid pendulum can be done with Newtonian mechanics. Newtonian mechanics is the formulation of classical mechanics that utilizes Newton's laws of motion, most importantly his second law \(\textbf{F}=m\mathbf{a}\). Classical mechanics is, as its name suggests, physics based on old-fashioned (or classical) notions of forces, determinism and absolute time. It does not account for relativistic effects nor quantum effects.
Given our second pendulum is in a moving reference frame and Newtonian mechanics does not easily adapt to alternative coordinate systems, like polar coordinates, Lagrangian mechanics makes the equations of motion easier to derive. Lagrangian mechanics also leads nicely into other fields of physics such as Hamiltonian mechanics, the Hamilton-Jacobi equation, quantum mechanics and relativity.
Figure shows an animation of the double rigid pendulum. This page does interactive simulations of this system if you would like to specify the parameter values yourself. Code Listing is the Julia code used to generate the above double pendulum animation. I will mention that the Julia code included in this article was largely generated with the help of ChatGPT.
Where we are using \(\dfrac{d^n f}{dx^n}\Big|_{x=a}\) to denote the \(n\)th derivative of \(f(x)\) evaluated at \(x=a\) and \(n!\) denotes the factorial of \(n\). If you are unfamiliar, well \(n!=n\times (n-1) \times (n-2) \times(n-3) \times ... \times 1\). For instance, \(5!=5\times 4 \times 3 \times 2 \times 1=120\). As for \(0!\) it is equal to 1. As for \(a\) it is an arbitrary number we get to choose. Equation (1) is known as the Taylor series of \(f(x)\). If we truncate our Taylor series at some \(n\) value, we will get an \(n\)th-order approximation for our function that is called a Taylor polynomial. For instance, if the maximum \(n\) value we substitute in is \(5\), we will get a fifth-order approximation to our function. Keep in mind that our \(n\)th-order approximation includes the \(n\)th derivative of our function evaluated at \(x=a\).
Why do these equations hold? Well, try taking the \(n\)th derivative of Equations (1) and (3) and substituting in \(x=a\) and \(x=0\), respectively. You will find that you get \(\dfrac{d^n f}{dx^n}\Big|_{x=a}\) and \(\dfrac{d^n f}{dx^n}\Big|_{x=0}\), respectively. Consequently, our series matches our original function in its \(n\)th derivative for \(n\in \mathbb{Z}^{+}\). Likewise, if you substitute in \(x=a\) and \(x=0\) into the Taylor and Maclaurin series, respectively, you should get \(f(a)\) and \(f(0)\), respectively. So we see that this is like a polynomial of infinite order that matches our original function for its value and derivatives value at one point. It turns out that this means it contains enough information to match our original function at other points, too.
There are exceptions where Taylor series do not accurately compute the function they pertain to. For instance, points where the function is undefined can mess things up. As an example, \(\ln{(x+1)}\)'s Maclaurin series will only approximate \(f(x)\) well for \(-1 < x \leq 1\) as at \(x=-1\) the function is undefined. Beyond these points, it will fail to converge (meaning it will not equal some finite number as terms for higher \(n\) will not get rapidly smaller as \(n\) gets bigger).
Now, I know this probably seems pretty abstract to you right now. But let us try to figure out the Maclaurin series for some example functions for which the \(n\)th derivative is fairly easy to calculate. Say, for instance, we calculate the Maclaurin series for \(e^x\). Why \(e^x\)? Because the \(n\)th derivative of \(e^x\) is just \(e^x\), and evaluating this at \(x=0\) yields 1. Hence:
is the Maclaurin series of \(e^x\). Returning to our previous discussion on order approximations, the first-order approximation to \(e^x\) based on this Maclaurin series would be the Maclaurin series terms up until \(n=1\). Which for \(e^x\) would be \(1+x\). Likewise, a second-order approximation of \(e^x\) would be \(1+x+\dfrac{x^2}{2}\). The higher order the approximation, the closer it is likely to be to the true value of our function.
Okay, let us try our hand at another function's Maclaurin series. How about \(\cos{x}\)? We know the first derivative of \(\cos{x}\) is \(-\sin{x}\). Hence the second derivative is \(-\cos{x}\). The third derivative would be \(\sin{x}\). Fourth derivative would be \(\cos{x}\). Fifth derivative would be \(-\sin{x}\) and sixth derivative would be \(-\cos{x}\). Well, I have noticed a pattern here! Seems to me like \((-1)^{\lfloor\frac{n+1}{2}\rfloor}\) (where \(\lfloor ... \rfloor\) rounds down decimals, e.g. it would take 3.6 and return 3) will recreate the sign of this function. If \(n\) is even, the trigonometric function will be \(\cos{x}\) and if it is odd it will be \(\sin{x}\). Evaluating these functions at \(x=0\), we see that if \(n\) is even we will get \(1\) from the trigonometric function and 0 if \(n\) is odd. Hence:
So our sum will essentially just be over even numbers. One way we can denote a sum over even numbers is by replacing \(n\) with \(2n\) and summing over all numbers. As \(2\) times any integer is always an even number. In this event, our \((-1)^{\lfloor\frac{n+1}{2}\rfloor}\) becomes:
We arrived at Equation (6) simply because \(n\) is an integer so adding a half to it should make no difference when we are rounding down. Consequently, our Maclaurin series becomes:
As our powers of \(x\) are all even in this series, a first-order approximation of \(\cos{x}\) based on this Maclaurin series would be just \(1\) (as the next term in the series would be \(-\dfrac{x^2}{2}\) which is second order and hence not included).
So here is some homework for you: try constructing the Maclaurin series for \(\sin{x}\). You should arrive at:
As another example, we will find the Maclaurin series for \(\ln{(x+1)}\) so we can see why it only converges well for \(|x| < -1\) where \(|x|\) is the absolute value of \(x\). The first derivative is \(\dfrac{1}{x+1}\). Second derivative is \(-\dfrac{1}{(x+1)^2}\). Third derivative is \(\dfrac{2}{(x+1)^3}\). Fourth derivative is \(-\dfrac{6}{(x+1)^4}\). So it seems to me that the pattern is that the numerator is \((-1)^{n-1} (n-1)!\) and the denominator is \((x+1)^n\). Hence:
If \(|x|>1\), we would expect the power of \(x\) in our numerator to potentially grow faster than \(n\) and hence our terms could become progressively larger as \(n\rightarrow \infty\). As for if \(x=\pm 1\), well our numerator would be smaller than our denominator, but our denominator would grow rather slowly, which means we would have to calculate a lot of terms to figure out what value it ends up equalling, assuming it does converge. If \(x=1\), we get:
Which is actually true. As this sum does, indeed, equal \(\ln{2}\). But because the denominator grows very slowly, we would need a lot of terms in the series in order to get a good approximation for what it equals. If \(x=-1\), then we get:
This sum does not converge, hence it actually equals \(\infty\). Hence why \(|x| < 1\) is a requirement for this Maclaurin series to converge, or at least converge at a reasonable pace, although it does also converge, albeit slowly, for \(x=1\).
Maclaurin and Taylor series have broad applications in physics. One application they have is in helping us connect more general and robust laws of physics to older approximations. For more on this, see the section on the classical limit of special relativity's kinetic energy.
Complex numbers are numbers that involve both a real and an imaginary part. That is, they are of the form \(a+bi\) where \(a\) and \(b\) are both real numbers and \(i\) is the imaginary number. \(a\) is called the real part of the number and \(b\) is called the imaginary part of the number. Importantly, \(a\) and \(b\) can be zero, consequently all real numbers are technically complex numbers. We can display complex numbers in the complex plane (also known as the Argand plane) as vectors. Specifically, the \(y\) component of this vector is the imaginary part of our number and the \(x\) component is the real part of the number.
Number 2+3i displayed in the complex plane.
Figure shows the number \(2+3i\) displayed in the complex plane. The length of the vector, \(l\), can be calculated using the Pythagorean theorem as \(l=\sqrt{2^2+3^2}=\sqrt{13}\). \(l\) can also be called the modulus of our complex number. As for \(\theta\), the angle from the positive \(x\)-axis measure counterclockwise it can be found using the definition of the tangent function as \(\theta =\tan^{-1}{\dfrac{3}{2}}\). Note also that \(3=l\sin{\theta}\) and \(2=l\cos{\theta}\) by the definition of these trigonometric functions.
Interestingly, these two qualities, the length of the complex number's vector and its angle, measured counterclockwise from the positive \(x\)-axis, can be used to uniquely define it. To see how, I must first share with you an interesting quality of the exponential function. Namely, that:
You may be thinking, so what? Well, powers of \(i\) have interesting properties. Namely, \(i^0=1\), \(i^1=i\), \(i^2=-1\), \(i^3=-i\) and \(i^4=1\). Generally, \(i^{4n}\) (where \(n\) is an integer) is equal to \(1\), \(i^{4n+1}\) is \(i\), \(i^{4n+2}\) is \(-1\) and \(i^{4n+3}\) is \(-i\).
An interesting thing to note that \(e^{iz}\) is that its modulus is one. How do I know this? Well, the modulus is defined as just the length of the complex number's vector in the complex plane, right? So for \(e^{iz}\) that would be:
\[\begin{align} \cos^2{z}+\sin^2{z}=1 \hspace{0.1cm} \forall z \in \mathbb{R}. \tag{14} \end{align}\]
Where \(\mathbb{R}\) is the set of real numbers. Okay, so getting back to how \(l\) and \(\theta\) can uniquely define a complex number. Well, interestingly you can write any complex number in the form \(le^{i\theta}\). Why? Well, recall that \(e^{i\theta}\) is just \(\cos{\theta}+i\sin{\theta}\). Looking at Figure we can clearly see that the \(x\) component of our vector is just \(l\cos{\theta}\), right? And we can also see that the \(y\) component is just \(l\sin{\theta}\) and if we expand our \(le^{i\theta}\) we get:
An example of a curve we might calculate the contour integral of in complex analysis. I have definitely not covered everything within the field of complex numbers. There's a field of maths known as complex analysis where we combine calculus and complex numbers. In it, we learn, among other things, how to integrate along curves (or contours) in the complex plane and that there is an extension of Taylor series to the complex plane called the Laurent series. In it, we write:
This is a contour integral over a curve \(C\) that includes the point \(z=z_0\). \(z_0\) is analogous to the \(a\) in our Taylor series as it is arbitrary. There's a formula called Cauchy's differentiation formula that says that:
Where \(f^{(n)}(z_0)\) is the \(n\)th derivative of \(f(z)\) evaluated at \(z=z_0\). Which helps us see how the Laurent series is connected to the Taylor series as for non-negative \(n\), \(a_n = \dfrac{f^{(n)}(z_0)}{n!}\). As for negative \(n\), \(a_n=0\) if \(f(z)\) is defined everywhere in the complex plane. Why do I mention this? Well, I personally consider complex analysis one of the most beautiful fields of mathematics and I thought I would mention it in case you are ever in a position to take a complex analysis class while at university.
Partial derivatives are just a straightforward extension of derivatives as you understand them already. The key difference is that they are derivatives of multivariable functions instead of single-variable functions. Further, when you differentiate with respect to one variable, all other variables are kept constant. If you would like to build a graphical image of what the partial derivative is, well recall that the derivative of a single-variable function is just the gradient of that function. Consequently, it is also the gradient of the tangent line to that function. The partial derivative is similar to that. As when we have a function with more than a single independent variable, we have the freedom to choose which variable or variables we wish to determine our function's gradient with respect to.
If you want to visualize this, imagine a surface defined by \(z=f(x,y)\) for example. Because a tangent line is two dimensional and we are in three dimensional space, there can be more than one tangent line to a given point. As when constructing the tangent line, we must answer a question: in which direction do we want our line to be tangential to our surface? It could be tangential in the \(x\) direction or the \(y\) direction, or even in any arbitrary direction in the \(xy\) plane. If we want the tangent line in the \(x\) direction, we will need the partial derivative with respect to \(x\) to get its gradient, whereas if we want the tangent line in the \(y\) direction, we will need the partial derivative with respect to \(y\) to get its gradient. More generally, for an arbitrary direction in the \(xy\) plane we would use the directional derivative as it is called.
Say \(f\) is a function of two variables — \(x\) and \(y\). Then its partial derivative with respect to \(x\) is formally defined as:
This is analogous to the first principles definition of the derivative you would have learned for standard derivatives. Namely, if we are differentiating \(f(x)\):
The only difference is that now we also have a variable \(y\) that our function \(f(x,y)\) depends on, but is kept constant when differentiating with respect to \(x\). Say \(f(x,y)=2x^2y\). Then \(\dfrac{\partial f}{\partial x}\) would be:
Did you notice that \(2y\) is a common factor of both terms in our numerator? Let us take it out of our limit altogether, as it is effectively a constant (it does not depend on \(h\), after all).
Okay, so that is the long way of finding out partial derivatives. Fortunately, there is also a faster way. Which is that we apply normal differentiation rules, but any variable we are not differentiating with respect to is treated like it is a constant. So for \(f(x,y)=2x^2y\) we would treat the \(2y\) as just a constant number and only differentiate the \(x^2\). Applying the power rule, we see that \(\dfrac{d}{dx}x^2 = 2x\) and hence:
Where \(u(x,t)\) is a function describing the temperature of the one-dimensional object (only one dimensional as the above heat equation only has a single spatial dimension, if we want more spatial dimensions, we will have to add second partial derivatives with respect to those other dimensions, too) we are modelling and \(\alpha\) is some constant. I know this equation may look confusing at first glance, but it is actually saying something rather intuitive to you.
Do you remember from your maths class that the second derivative of a function is its concavity? So if the second derivative is negative, that means our function is concave down — it is leading to some sort of maximum. Whereas if it is positive, the function is concave up, which means it is going up from some minimum. We have the second derivative with respect to space on the right-hand side of Equation (18), so it essentially returns positive if we have a localized colder area and neighbouring hotter points. Whereas it returns negative if we have a really hot point surrounded by cooler points. The left-hand side of Equation (18), however, represents the rate of change of our function in time.
Equation (18) therefore essentially says that if we are in a region where there is a really cold point surrounded by hotter points, the temperature will increase in the short-term for that colder point. Whereas the equation says that the temperature will decrease in a hotter region surrounded by colder points. If you have ever brought something hot out of the oven, or put something of room temperature into the fridge or freezer, this should make intuitive sense to you.
Code Listing solves the heat equation in 3D for a \(100^{\circ}C\) sphere in a \(20^{\circ}C\) room.
Heat equation simulation code.
#!/usr/bin/env julia
using Pkg
# Install missing packages automatically.
for package in ("FFTW", "GLMakie")
if !haskey(Pkg.project().dependencies, package)
Pkg.add(package)
end
end
using FFTW
import GLMakie
using Printf
# ============================================================
# Configuration
# ============================================================
const T_ROOM = 20.0
const T_BALL = 100.0
const ALPHA = 1e-5
const RADIUS = 0.10
const LX = 1.0
const LY = 1.0
const LZ = 1.0
const NX = 64
const NY = 64
const NZ = 64
const SIMULATION_TIME = 1800.0
const NUMBER_OF_FRAMES = 600
const FRAME_RATE = 20
const OUTPUT_FILE = "heat_equation_3d.gif"
# Smooth transition between the hot region and room temperature.
const TRANSITION_CELLS = 6.0
# RKF45 tolerances.
const RELTOL = 1e-7
const ABSTOL = 1e-6
const INITIAL_DT = 0.05
const MAX_DT = 2.0
const MIN_DT = 1e-9
# Conservative explicit-RK stability restriction.
const STABILITY_FACTOR = 0.50
# ============================================================
# Spatial grid
# ============================================================
dx = LX / NX
dy = LY / NY
dz = LZ / NZ
x = collect((0:NX-1) .* dx .- LX / 2)
y = collect((0:NY-1) .* dy .- LY / 2)
z = collect((0:NZ-1) .* dz .- LZ / 2)
# ============================================================
# Smooth initial hot sphere
# ============================================================
const TRANSITION_WIDTH = TRANSITION_CELLS * max(dx, dy, dz)
function smootherstep(s)
return s^3 * (10.0 + s * (-15.0 + 6.0 * s))
end
function initial_temperature(r)
inner_radius = RADIUS - TRANSITION_WIDTH / 2
outer_radius = RADIUS + TRANSITION_WIDTH / 2
if r <= inner_radius
return T_BALL
elseif r >= outer_radius
return T_ROOM
else
s = (r - inner_radius) / TRANSITION_WIDTH
weight = 1.0 - smootherstep(s)
return T_ROOM + (T_BALL - T_ROOM) * weight
end
end
T = Array{Float64}(undef, NX, NY, NZ)
for k in 1:NZ
for j in 1:NY
for i in 1:NX
r = sqrt(x[i]^2 + y[j]^2 + z[k]^2)
T[i, j, k] = initial_temperature(r)
end
end
end
# ============================================================
# Fourier spectral Laplacian
# ============================================================
kx = 2π .* FFTW.fftfreq(NX, 1 / dx)
ky = 2π .* FFTW.fftfreq(NY, 1 / dy)
kz = 2π .* FFTW.fftfreq(NZ, 1 / dz)
KX = reshape(kx, NX, 1, 1)
KY = reshape(ky, 1, NY, 1)
KZ = reshape(kz, 1, 1, NZ)
lambda = -ALPHA .* (
KX.^2 .+
KY.^2 .+
KZ.^2
)
function heat_rhs(u, lambda)
return real.(ifft(lambda .* fft(u)))
end
# ============================================================
# RKF45
# ============================================================
function rkf45_step(u, h, lambda)
k1 = heat_rhs(u, lambda)
k2 = heat_rhs(
u .+ h .* (1 / 4) .* k1,
lambda
)
k3 = heat_rhs(
u .+ h .* (
(3 / 32) .* k1 .+
(9 / 32) .* k2
),
lambda
)
k4 = heat_rhs(
u .+ h .* (
(1932 / 2197) .* k1 .-
(7200 / 2197) .* k2 .+
(7296 / 2197) .* k3
),
lambda
)
k5 = heat_rhs(
u .+ h .* (
(439 / 216) .* k1 .-
8 .* k2 .+
(3680 / 513) .* k3 .-
(845 / 4104) .* k4
),
lambda
)
k6 = heat_rhs(
u .+ h .* (
-(8 / 27) .* k1 .+
2 .* k2 .-
(3544 / 2565) .* k3 .+
(1859 / 4104) .* k4 .-
(11 / 40) .* k5
),
lambda
)
# Fourth-order estimate.
u4 = u .+ h .* (
(25 / 216) .* k1 .+
(1408 / 2565) .* k3 .+
(2197 / 4104) .* k4 .-
(1 / 5) .* k5
)
# Fifth-order estimate.
u5 = u .+ h .* (
(16 / 135) .* k1 .+
(6656 / 12825) .* k3 .+
(28561 / 56430) .* k4 .-
(9 / 50) .* k5 .+
(2 / 55) .* k6
)
return u5, u4
end
# ============================================================
# Stable timestep restriction
# ============================================================
lambda_max_abs = maximum(abs.(lambda))
dt_stability = STABILITY_FACTOR / lambda_max_abs
@printf(
"Maximum |lambda| = %.8f s^-1\n",
lambda_max_abs
)
@printf(
"RKF45 stability timestep limit = %.8f s\n",
dt_stability
)
# ============================================================
# Adaptive integration
# ============================================================
function integrate_to!(u, t, target, h, lambda)
while t < target
h = min(
h,
MAX_DT,
dt_stability,
target - t
)
if h < MIN_DT
error(
"RKF45 timestep fell below MIN_DT at t = $t"
)
end
u5, u4 = rkf45_step(u, h, lambda)
scale =
ABSTOL .+
RELTOL .* max.(abs.(u), abs.(u5))
error_norm =
maximum(
abs.(u5 .- u4) ./ scale
)
if error_norm <= 1.0
u .= u5
t += h
end
factor =
if error_norm == 0.0
5.0
else
clamp(
0.9 * error_norm^(-0.2),
0.2,
5.0
)
end
h = min(
MAX_DT,
dt_stability,
h * factor
)
end
return t, h
end
# ============================================================
# GLMakie visualisation
# ============================================================
GLMakie.activate!()
fig = GLMakie.Figure(
size = (1000, 800)
)
ax = GLMakie.Axis3(
fig[1, 1],
aspect = (1, 1, 1),
xlabel = "",
ylabel = "",
zlabel = "",
title = ""
)
# ============================================================
# Temperature colour map
#
# 20 °C is opaque white, matching the background.
# ============================================================
temperature_colormap = [
GLMakie.RGBAf(1.0, 1.0, 1.0, 1.0), # 20 °C
GLMakie.RGBAf(0.05, 0.10, 0.80, 1.0),
GLMakie.RGBAf(0.0, 0.65, 1.0, 1.0),
GLMakie.RGBAf(0.0, 0.90, 0.45, 1.0),
GLMakie.RGBAf(1.0, 0.90, 0.0, 1.0),
GLMakie.RGBAf(1.0, 0.35, 0.0, 1.0),
GLMakie.RGBAf(0.85, 0.0, 0.0, 1.0)
]
# Makie expects volume dimensions as two endpoints.
volume_plot = GLMakie.volume!(
ax,
(x[1], x[end]),
(y[1], y[end]),
(z[1], z[end]),
T;
algorithm = :mip,
colormap = temperature_colormap,
colorrange = (T_ROOM, T_BALL)
)
# ============================================================
# Colourbar
# ============================================================
GLMakie.Colorbar(
fig[1, 2],
volume_plot;
label = "Temperature (°C)",
ticks = (
collect(20.0:10.0:100.0),
string.(collect(20.0:10.0:100.0))
)
)
# ============================================================
# Simulation time display
# ============================================================
time_label = GLMakie.Label(
fig[2, 1],
"Simulation time: 0.00 s";
tellwidth = false,
fontsize = 20
)
# ============================================================
# Animation
# ============================================================
frame_times = collect(
range(
0.0,
SIMULATION_TIME;
length = NUMBER_OF_FRAMES
)
)
u = copy(T)
# Keep mutable animation state local to the record callback.
let t = 0.0,
dt = min(INITIAL_DT, dt_stability)
GLMakie.record(
fig,
OUTPUT_FILE,
enumerate(frame_times);
framerate = FRAME_RATE
) do (frame_number, target_time)
if frame_number > 1
t, dt = integrate_to!(
u,
t,
target_time,
dt,
lambda
)
end
# Update the volume with the actual temperature field.
volume_plot[4] = u
# Update simulation time.
elapsed_minutes = floor(Int, target_time / 60)
remaining_seconds = target_time - 60 * elapsed_minutes
time_label.text =
@sprintf(
"Simulation time: %02d min %04.1f s",
elapsed_minutes,
remaining_seconds
)
# Console diagnostics.
Tmin = minimum(u)
Tmax = maximum(u)
@printf(
"Frame %4d/%d | t = %02d min %04.1f s | dt = %.5f s | T range = %.8f–%.8f °C\n",
frame_number,
NUMBER_OF_FRAMES,
elapsed_minutes,
remaining_seconds,
dt,
Tmin,
Tmax
)
end
end
println()
println("Animation written to: $OUTPUT_FILE")
Animation showing the heat distribution of an object and how it changes over time.
When we wish to denote a multi-term product, we can use the product notation \(\displaystyle \prod_{i=1}^n a_i\). This essentially says that we multiply \(a_1\), \(a_2\), \(a_3\) and so on until \(a_n\). It is similar to the summation notation \(\displaystyle \sum_{i=1}^n a_i\), with the difference being that instead of addition signs being between each term we have multiplication signs instead.
For instance, for the product \(\displaystyle \prod_{i=1}^n 2i-1\) we would multiply \(2i-1\) for \(i=1\), \(i=2\), \(i=3\), and so forth up until \(i=n\). If we set \(n=3\), then:
Matrices are very important in physics and mathematics. In fact, the first formulation of quantum mechanics to be developed was based on matrices and is also called matrix mechanics. Further, vectors are a type of matrix. General relativity and quantum field theory also make extensive use of tensors, which can be thought of as an extension of matrices. Further, when you fit a line of best fit to a scatter plot this involves matrices.
Matrices have two potential dimensions — rows and columns. As such the dimensions or size of a matrix is described as being \(m\times n\) where \(m\) is the number of rows and \(n\) is the number of columns. If a matrix has an equal number of rows and columns, it is said to be a square matrix. For instance:
is a square matrix of size \(2\times 2\). If we want to refer to a specific element of this matrix, we can use its row number and column number. For instance: \(A_{1,1} = 1\) and \(A_{2,2}=4\).
Vectors are a type of matrix; specifically, they are one-dimensional matrices. Either they only have one row (in which case they are a row vector) or one column (in which case they are a column vector).
Means that \(\mathbf{C}\) has elements that are equal to the corresponding element of \(\mathbf{A}\) minus the corresponding element in \(\mathbf{B}\). For instance:
If you multiply two matrices, you multiply the elements along the corresponding row of the first matrix by the elements of the corresponding column of the second matrix and sum them up. For instance, say we multiplied \(\mathbf{A}\) by this matrix:
As you can see the first row first column element of the product matrix was obtained by multiplying the first row of \(\mathbf{A}\) by the first column of \(\mathbf{B}\). Likewise, the second row first column element of the product matrix was obtained by multiplying the second row of \(\mathbf{A}\) by the first column of \(\mathbf{B}\).
Due to how we multiply matrices, the matrix product is only defined if we are multiplying a \(m\times n\) matrix by a \(n\times p\) matrix. The number of columns of the first matrix must match the number of rows of the second. The result of this multiplication will be a \(m\times p\) matrix. Further, because of this definition of matrix multiplication, the operation is non-commutative. In other words, the order in which we multiply matrices matters. So that if we left-multiply one matrix, say \(\mathbf{A}\), by another, say \(\mathbf{B}\), this is not the equivalent to right-multiplying \(\mathbf{A}\) by \(\mathbf{B}\). In other words, in general:
Most square matrices like \(\mathbf{A}\) can be inverted. This is the matrix equivalent to the reciprocal. So if you want to solve the equation: \(3x=5\) you would multiply both sides by \(\dfrac{1}{3}\) because this is the reciprocal of \(3\), the coefficient of \(x\). Whereas to solve \(\mathbf{A}\mathbf{x}=\mathbf{b}\) we could multiply both sides by \(\mathbf{A}^{-1}\), the inverse of \(\mathbf{A}\), to get:
That being said, as we will see in the Gaussian elimination section, there is a more efficient way of solving such equations. What is \(\mathbf{I}\)? It is the so called identity matrix. It is essentially the square matrix equivalent to \(1\). As if you multiply it by any matrix with the required dimensions to multiply with it, multiplication by it should not change the matrix at all. Its elements are ones down the main diagonal and zero in all other elements. For instance, the \(2\times 2\) identity matrix is:
I should also mention that some square matrices have no inverse. This is usually the case when one or more rows can be written as linear combinations of the other rows. For instance:
It is also possible for a matrix to be invertible, but for inverting the matrix to not be a great idea for another reason. Beyond invertibility, when dealing with a square matrix we also often care about its condition number. A matrix with a large, yet finite condition number may be technically invertible but even small errors (such as due to floating point arithmetic errors) in the elements of that matrix can massively change the contents of its inverse. Whereas a matrix with a condition number close to one should not suffer this problem at all. I should also mention that singular matrices have an infinite condition number.
And yes, \(\mathbf{x}\) and \(\mathbf{b}\) are both column vectors. Typically, in these equations \(\mathbf{A}\) is a square matrix. If it is a square matrix, we will get exact solutions to our equation.
If it has more rows than columns, then we have an overdetermined system and our solution for \(\mathbf{x}\) will be approximate. Overdetermined systems arise when we are fitting lines of best fit to bivariate data. In that example, you will notice that some of the scatter plot data will not be exactly on the line of best fit. This is precisely because of the approximate nature of our solution. Underdetermined systems have the opposite issue, as we have more columns than rows. This gives us freedom to choose one or more elements of our solution vector \(\mathbf{x}\).
So how do we invert a matrix? We use something analogous to the elimination method of solving simultaneous equations. Specifically, a technique called Gaussian elimination. We can also adapt this technique to solve matrix equations like Equation (73). To invert \(\mathbf{A}\) we first augment it with \(\mathbf{I}\):
Our aim in inverting \(\mathbf{A}\) is to turn the left of this augmented matrix into the identity matrix. At this point we can read \(\mathbf{A}^{-1}\) off the right side of the augmented matrix.
If we want to solve Equation (73), we use a similar procedure. Except we put \(\mathbf{b}\) in place of \(\mathbf{I}\) when we form the augmented matrix. The aim is still to convert the \(\mathbf{A}\) to \(\mathbf{I}\):
We will do the same row operations. First we will multiply row 1 by 2 and replace row 1 with it. We will denote this operation as \(2R_1 \rightarrow R_1'\):
Another matrix concept I should probably cover with you is called the determinant. It is a single number value you can obtain from the elements of a square matrix. For a matrix of size \(2\times 2\) it is defined as:
\[\begin{alignedat}{3} \det\begin{bmatrix} a & b \\ c & d \end{bmatrix} &= \begin{vmatrix} a & b \\ c & d \end{vmatrix} \\ &= ad-bc. \end{alignedat}\]
It gets more complex with bigger matrices. For instance, for a \(3\times 3\) matrix it is:
If the determinant is zero, the matrix will be singular. This is because the inverse of a square matrix can be calculated in terms of the reciprocal of the determinant.
then \(\lambda\) is said to be an eigenvalue of \(\mathbf{A}\) and \(\mathbf{x}\) is an eigenvector of \(\mathbf{A}\). A square matrix of dimensions \(n\times n\) will have \(n\) distinct eigenvalues and eigenvectors. Each eigenvector will be of dimensions \(n\times 1\). Interestingly, each eigenvector of a matrix is orthogonal to the others. In other words, they are perpendicular to each other — the angle between them is \(90^{\circ}\). This also means that their dot product will be zero.
We solve for \(\lambda\) by solving the polynomial equation that results from:
Where \(\det{\left(\mathbf{A}-\lambda \mathbf{I}\right)}\) denotes the determinant of matrix \(\mathbf{A}-\lambda \mathbf{I}\) and \(\mathbf{I}\) is the identity matrix. Then we figure out \(\mathbf{x}\) by solving:
When we solve for the eigenvectors, we will find that one unknown is left and this means that the scaling of the vector is arbitrary. Often we choose the scaling to make it so that \(\mathbf{x} \cdot \mathbf{x} = 1\). When this condition is satisfied we say that our eigenvectors are normalized. Say, for example, we have the matrix:
It might seem like we need to solve two equations here, but with eigenvector problems for \(2\times2\) matrices the two equations end up containing the same information. So in this case we only need to solve one.
Given we do later cover the Newton-Kantorovich method, which is closely related to Newton's method, I thought I should probably cover Newton's method here. Newton's method, which is also known as the Newton-Raphson method, is a method for solving nonlinear algebraic equations, including systems of nonlinear algebraic equations. For instance, say we wanted to solve:
\[\begin{aligned} x = \cos^2{x}. \end{aligned}\]
Then Newton's method would provide us a way to do so. Newton's method essentially finds the root of a function by looking at where its tangent line intersects the \(x\) axis. Another way to think about it is that it uses the first two terms (the constant term and the linear term) of the function's Taylor series to determine its \(x\) intercept.
For our example, we would rearrange it to make it a function whose root we are finding, namely:
\[\begin{aligned} f(x) &= x -\cos^2{x} \\ &= 0. \end{aligned}\]
Then Newton's method says we can apply this scheme to find its zero:
Where \(x_n\) is our \(n\)th approximation to \(x\). \(x_0\) will be our first guess as to \(f(x)\)'s root. Newton's method will not always converge towards a solution if our initial guess is bad enough. Getting back to our example root-finding problem, I would guess \(x\in[0,1]\) would be where we would find the root for \(f(x)\). \(\cos^2{x}\) is always between \(0\) and \(1\) for all real \(x\), hence \(x\in[0,1]\) sounds like a viable solution. Let us try \(x=1\) as our first guess. Differentiating \(f(x)\) yields:
If we continue further iterations of Newton's method, we will find that \(x_n\) stays at \(0.6417144\) when rounding to seven decimal places.
When I am left with only a pen and paper and nothing to do, sometimes I will actually use Newton's method to approximate square roots without a calculator. For instance, say we wanted to find \(\sqrt{2}\). We could solve the equation:
\(\mathbf{x}_{n}\) is a column vector of our \(n\)th approximation to the independent variables that our system of equations depends on. \(\mathbf{f}_n\) is our system of equations written as a vector of functions we are simultaneously setting to zero evaluated at \(\mathbf{x}=\mathbf{x}_n\). \(\mathbf{J}_n\) is the Jacobian matrix evaluated at \(\mathbf{x}=\mathbf{x}_n\). Let the elements of \(\mathbf{x}_n\) and \(\mathbf{f}_n\) be numbered \(1\) to \(m\) (where \(m\) is the number of equations we are solving). What is the Jacobian matrix? Well, it is a matrix with elements (Boyd, 2000, p. 526):
We can rewrite \(y\) in terms of \(x\) in the second equation, yielding:
\[\begin{aligned} y &= \pm \sqrt{9-x^2}. \end{aligned}\]
Hence \(x\in [-3,3]\) and \(y\in [-3,3]\). \(x+y>0\) thanks the logarithm in the first equation, hence \(y>-x\). Let us choose \(x=2\) and \(y=+\sqrt{9-2^2}=\sqrt{5}\) as a first guess.
Newton's method solution to $\mathbf{f}=\mathbf{0}$ with initial guess $x=2$ and $y=\sqrt{5}$.
using LinearAlgebra
function newton_system()
# Initial guesses
x = 2.0
y = sqrt(5)
# Iteration parameters
tol = 1e-12
maxiter = 100
iteration_error = 1;
n = 0;
while iteration_error > tol
n += 1
s = x + y
# Residual vector
F = [
x*y - log(s),
x^2 + y^2 - 9
]
# Jacobian matrix
J = [
y - 1/s x - 1/s
2x 2y
]
# Newton correction
Δ = J \ F
# Update solution
x -= Δ[1]
y -= Δ[2]
# Correction magnitude
iteration_error = norm(Δ, Inf)
println("Iteration $n: correction magnitude = $iteration_error")
end
println("\nNumerical solution:")
println("x = $x")
println("y = $y")
return x, y
end
x, y = newton_system()
Fourier series are a way of rewriting periodic functions in terms of sine and cosine waves. Specifically, if we wish to write \(f(x)\) as a Fourier series over the domain \(x \in [-L,L]\), we would write (keep in mind the series coefficients \(a_n\) and \(b_n\) are not the same as those we have been using so far):
As this article involves a lot of differential equations, I thought I should cover how we categorize and solve differential equations. Originally, this was in the prerequisite mathematics section but given how important differential equations are in physics, I decided to give it its own separate section. This is definitely not intended to be a comprehensive covering of this topic. As this is a topic so broad that entire textbooks are written about even just one method for solving differential equations.
Differential equations are equations that involve the derivatives of a function and typically the aim in solving them is to determine the original function they pertain to. For instance, say you had the uncoupled, linear, homogeneous, first-order ordinary differential equation:
\[\begin{align} y' &= y. \tag{23} \end{align}\]
Our aim would be to determine what \(y\) is.
I also showed you this equation to clarify some of the terminology we use with regards to differential equations. So why is this equation uncoupled? Because it is a single equation and not a series of differential equations we need to solve simultaneously. Why is this equation linear? Well, it is because there is no term that is nonlinear in \(y\) or its derivative(s). For instance, if the equation was \(y'=y^2\), that would make it nonlinear because the right-hand side is nonlinear in \(y\). Likewise \(\cos{y'}=y\) is also nonlinear as it is nonlinear in \(y'\).
Why is it an ordinary differential equation (ODE)? Because there are only ordinary derivatives, not partial derivatives. Why is it homogeneous? Because there are no terms that do not involve \(y\) or its derivative(s). Why is it first order? Because the highest order derivative in the equation is the first derivative.
I should also tell you that because differentiating deletes constants from our function, in order to obtain a unique solution to a given differential equation of order \(n\), we need \(n\) additional conditions beyond the differential equation itself. Often these conditions are initial conditions, that is they specify the initial state of our system. In this event, our differential equation is called an initial value problem. For instance, if we wanted to study \(\ddot{x}=-g\) over \(t \in [0, 10]\) then the appropropriate initial conditions could be \(x(0)=50\) and \(\dot{x}(0)=0\), as these specify the initial state of our system.
Other conditions are possible, too. For instance, boundary conditions could also be used for our ODE \(\ddot{x}=-g\). As the term suggests, boundary conditions involve the values of our function and/or its derivatives at the endpoints (or boundary) of our domain. For this problem, the appropriate boundary conditions could be the values of \(x(0)\) and \(x(10)\). In this case, we would call the problem a boundary value problem. We could also have the conditions \(\dot{x}(2)=50\) and \(x(5)=10\), which together do not really fit neatly into the definitions of either initial or boundary conditions.
Where \(p>0\), \(r\geq 0\). \(r(x)\) is referred to as the weight function. There are also boundary conditions imposed as part of a Sturm-Liouville problem, namely (Lebl, 2025) :
Where \(\alpha_1\) and \(\alpha_2\) cannot both be simultaneously zero and nor can \(\beta_1\) and \(\beta_2\). \(\lambda\) can take on a set of discrete values, which are called eigenvalues. Each eigenvalue corresponds to a different solution \(y\) which is called the corresponding eigenfunction. We usually order the eigenvalues, and the corresponding eigenfunctions, by the absolute value of the eigenvalue in ascending order. So the first eigenvalue is the one with the smallest absolute value and the first eigenfunction is the eigenfunction corresponding to the eigenvalue with the lowest absolute value.
An interesting quality of eigenfunctions is that they are orthogonal (similarly to the eigenvectors of a matrix). That means that:
Where \(c_m\) is some constant and \(\langle y_m | y_n \rangle\) is called the inner product between \(y_m\) and \(y_n\). Interestingly, the dot product between two vectors is also referred to as the inner product. Just like the function inner product, the dot product also yields zero if two vectors are orthogonal. There are a lot of parallels between Sturm-Liouville theory and the study of matrices and vectors.
There are several analytic, in other words exact, methods for solving differential equations. They include rearranging the differential equation to be in a integrable form, Laplace transforms, power series solutions, separation of variables, and Fourier series solutions.
For Equation (23), there would be a few ways we could solve this differential equation. As luckily each of the adjectives we used to describe it implies it should be easy to solve. One option is we could divide both sides by \(y\) and integrate on \(x\):
\[\begin{aligned} \int \dfrac{\dfrac{dy}{dx}}{y} dx &= \int dx \\ \int \dfrac{dy}{y} &= \int dx \\ \ln{y} &= x + C \end{aligned}\]
Exponentiating both sides yields:
\[\begin{aligned} y &= e^{x+C}. \end{aligned}\]
Note that we have one unknown constant, \(C\). This is a product of how derivatives delete constants and is why we need initial, boundary or other conditions to uniquely determine our solution. For instance, if \(y(0)=1\), then we can substitute this into our solution to find \(C\).
The \(C_0\) between the last two lines are not the same; as they are arbitrary constants we do not need to keep them strictly the same between these lines.
We ommitted \(n=0\) from the \(y'(x)\) power series because the derivative of \(x^0=1\) is zero. For the sake of consistency, let us rewrite our derivative power series in terms of \(x^n\) instead of \(x^{n-1}\). So do this, we replace \(n\) with \(n+1\) under the sum and to compensate for this, we reduce the bounds on our sum by one.
\[\begin{aligned} y &= \sum_{n=0}^{\infty} \dfrac{x^n}{n!}. \end{aligned}\]
Which we can recognize as the Maclaurin series of \(e^x\). I guess we could have more directly used our knowledge of Maclaurin series and the fact that \(y'=y\) implies that:
\[\begin{aligned} \dfrac{d^n y}{dx^n} = y. \end{aligned}\]
for \(j\in \{1,2,3,...,n\}\). This is really just a polynomial equation of degree \(n\) that we need to solve and \(r_j\) is just the \(j\)th solution to this equation. For \(y'=y\), for instance \(a_0=-1\) and \(a_1=1\) and hence we need to solve:
And with \(y(0)=1\) we obtain \(C_1=1\). Hence \(y(x)=e^x\). To see how it works, let us try to solve \(y'''+6y''+11y'+6y=0\). Hence our polynomial equation is:
Substituting \(r_j=-1\) into the left-hand side of this equation yields \(0\). Hence \(r_j+1\) is a factor. Using synthetic division (polynomial long division will work equally well) we get:
Where \(s\) is a complex number. It is invertible, although the inverse Laplace transform requires some knowledge of complex analysis to define, so I am going to skip the definition. The Lapace transform of derivatives is also well-known:
To see the power of this approach, let us consider the equation:
\[\begin{aligned} y'' - y &= \cos{x}. \end{aligned}\]
The Laplace transform of \(y''\) is \(s^2 \mathcal{L}(y) - sy(0) - y'(0)\). As for the \(\cos{x}\) its Laplace transform is \(\dfrac{s}{s^2+1}\). Hence our differential equation becomes
I thought I should cover one technique for solving partial differential equations, too. Say we had the heat equation, Equation (18). Then, if we are using the separation of variables technique, we would assume that \(u(x,t)\) can be written as \(u(x,t)=X(x)T(t)\). Then Equation (18) becomes:
The left-hand side depends only on \(t\) and the right-hand side only depends on \(x\). Hence both sides must equal a constant, which we will call \(-\lambda\). The importance of the negative sign will become apparent soon. Hence we can write a pair of ordinary differential equations we need to solve. For \(T(t)\), the equation is:
These are both linear, homogeneous differential equations with constant coefficients. Hence, our solutions will involve exponential functions. Solving the polynomial equations we get from this knowledge yields:
So this is why we had opted to give \(\lambda\) a negative sign earlier. As real exponentials will not satisfy our boundary conditions of \(X(0)=X(L)=0\) without \(C_2\) and \(C_3\) both being zero. The \(C_2\) and \(C_3\), which are arbitrary constants, that were used in Equation (32) will be different to those in Equation (31). Then we apply our boundary and initial conditions, which are often of the form:
Where \(x\in [0,L]\) is our spatial domain and \(f(x)\) is some specified function. We will impose our spatial boundary conditions on \(X(x)\), \(X(0)=0\) implies that:
Hence we do not have a just a singular solution for \(\lambda\) and we should really call it \(\lambda_n\) to reflect this reality. \(X(x)\), \(T(t)\) and \(u(x,t)\) all depend on \(\lambda_n\) and hence should get a \(n\) subscript.
Why have I given the constants \(n\) indices? Because they, too, could vary between terms with different \(\lambda\). Why the \(|n|\)? Well, we square rooted \(n^2\), so it will be the absolute value of \(n\). We will call \(C_{1n}C_{3n}\), \(a_n\) when we write \(u_n(x,t)\): Hence:
Keep in mind that \(u_{-n}(x,t)=u_n(x,t)\) and that \(u_0=0\) (as \(\sin{0}=0\)), hence we only need to sum over \(n \in \mathbb{Z}^{+}\). Hence, we obtain the following series as our solution:
How can we determine \(a_n\) from this? Let us investigate what happens if we multiply this by \(\sin{\left(\dfrac{n \pi}{L} x\right)}\) and integrate over \(x\in [0,L]\):
\(m+n\) and \(m-n\) is always an integer so the sines should be zero. \(\sin{0}=0\), too. Hence, we will get \(0\) from this if \(m\neq n\). If \(m=n\) though, we end up dividing by 0 for the first term, which means we cannot simply declare it zero. So we will need to take the limit as \(m\) approaches \(n\) to determine the value of the first integral at its upper bound:
Here we have used the fact that \(\delta_{mn}\) is zero if \(m\neq n\) and one if \(m=n\) and hence the only non-zero term corresponds to \(m=n\). Hence we can calculate \(a_n\) as:
Interestingly, Equation (33) is called the Fourier series decomposition of \(f(x)\) in terms of sines only. From Equation (22), we can see our \(b_n\) here matches the \(a_n\) from the \(u_n(x,t)\), except that \(a_n\) is calculated by integrating only over \(x\in [0,L]\). So what is up with this? Well, interestingly we can only represent \(f(x)\) solely with sine terms if and only if \(f(x)\) is an odd function, just like \(\sin{\left(\dfrac{n\pi x}{L}\right)}\) itself. Meaning that \(f(-x)=-f(x)\). Hence we can split our \(b_n\) integral as:
In our first integral, we will replace \(x\) with \(-x\) and hence \(dx\rightarrow-dx\) and our domain becomes \(x\in [L, 0]\) instead of \(x\in [-L, 0]\).
So we see that our \(a_n\) from \(u_n(x,t)\) are in fact equivalent to \(b_n\), at least for odd functions.
I should also mention that while Fourier series are technically intended for periodic functions, our function actually does not need to repeat itself within the domain we are calculating it for. Further, how the function behaves outside that domain is irrelevant to the calculation of Fourier series. So the Fourier series can, in fact, match our function perfectly within our domain despite not actually being periodic. Although, this lack of periodicity will cause the Fourier series and the original function to not match outside the domain in which we calculated the series.
Interestingly, our differential equation for \(X_n\) is an example of a Sturm-Liouville problem. \(X_n\) were the eigenfunctions and \(\lambda_n\) were the eigenvalues. The orthogonality quality of eigenfunctions is quite useful to us when we are solving linear partial differential equations using separation of variables and at least one of the equations we get from this is a Sturm-Liouville problem. As it often makes finding the coefficients of the series expansion of our solution easier. Another partial differential equation whose solution gives rise to Sturm-Liouville problems is the Schrödinger equation.
In this article, however, we will encounter differential equations that have no exact solutions and for which numerical solutions are necessary. Numerical solution methods approximate the solution to a differential equations, and as such they are not exact. Although, quite often we can make them as accurate as we need them to be (even greater than ten significant figures).
Typically for classical mechanical systems, we will have initial value problems, so in this section we will cover numerical methods for initial value problems.
Numerical solutions are actually quite interesting, because they typically involve applications of the Taylor series that we have covered. For instance, say we wanted to numerically integrate the differential equation \(y'=y\) with initial condition \(y(0)=1\). Then if we wanted to approximate \(y(h)\) for some small \(h\), we could use the Maclaurin series of \(y\):
Now our differential equation makes it very easy to approximate any arbitrary-order derivative of \(y\) at \(x=0\), as we can just keep differentiating our differential equation and find that \(\dfrac{d^n y}{dx^n} = y\) for any \(n\in \mathbb{Z}^{+}\). But say we did not have that luxury. Then what we could do is just approximate \(y(h)\) using the first two terms of the Maclaurin series:
\[\begin{aligned} y(h) &\approx y(0) + hy'(0) \\ &= 1 + h \cdot 1 \\ &= 1 + h. \end{aligned}\]
We can then approximate \(y(2h)\) using the same method:
And continue on from there. This method, where we truncate the Taylor series at the first two terms and numerically approximate our solution by applying this approximation at each step, is called Euler's method. As we ignore so many terms in the Taylor series, this method is rather inaccurate. Specifically, we call it a first-order method.
Other schemes for numerical integration of ordinary differential equations also exist. Among the most popular are the Runge-Kutta family of methods, such as the Runge-Kutta fourth-order method. These methods do not utilize higher-order derivatives, but they use clever tricks for approximating the solution to higher-order accuracy using only first-order derivatives. I should say that Euler's method and the Runge-Kutta methods are all only applicable when we have initial conditions, not boundary or other conditions. There are other integration schemes for ODEs that work well with these other conditions, however.
To illustrate how we use these methods, let us try to solve the differential equation:
\[\begin{aligned} y' &= y, \hspace{0.2cm} y(0)=1. \end{aligned}\]
So our starting point is going to be \(x=0\). We will call this point \(x_0\); the value of \(y\) at \(x_0\) we will call \(y_0\). The fourth-order Runge-Kutta method, says that we should approximate \(y\) at \(x_0+h\) for the differential equation:
And we should repeat this process for all subsequent points we wish to approximate \(y(x)\) at. That is why, when we write numerical integration schemes like this we usually use \(x_i\) to denote the \(i\)th \(x\) value for which we are approximating \(y\).
In Code Listing , I have implemented both Euler's method and the Runge-Kutta fourth-order method to solve this differential equation. The results are displayed, along with the exact solution, in a table below the code. Here we used \(h=0.2\) and continued the approximation for five steps, until \(x=1\). As you can see, the Runge-Kutta fourth-order method is much more accurate than Euler's method.
Differential equation solution code.
using DataFrames;
N = 5;
a = 0;
b = 1;
h = (b-a)/N;
x = LinRange(a, b, N+1);
yEul = ones(N+1);
yRK4 = ones(N+1);
function f(x, y)
return y;
end
for i in 1:N
yEul[i+1] = yEul[i] + h*f(x[i], yEul[i]);
k1 = h*f(x[i], yRK4[i]);
k2 = h*f(x[i]+h/2, yRK4[i]+k1/2);
k3 = h*f(x[i]+h/2, yRK4[i]+k2/2);
k4 = h*f(x[i]+h, yRK4[i]+k3);
yRK4[i+1] = yRK4[i] + (k1 + 2*k2 + 2*k3 + k4)/6;
end
df = DataFrame(x = x, Euler = yEul, RK4 = yRK4, Exact = exp.(x));
show(stdout, MIME("text/plain"), df)
println()
An arguably better method for numerically solving ordinary differential equations is the Runge-Kutta-Fehlberg fourth/fifth-order method (RKF45), as it adapts our step size \(h\) to ensure that the error in our solution never exceeds a certain threshold. In this method, we use:
Here \(\epsilon\) is the maximum absolute error in our approximation we are willing to accept. \(\mathrm{TE}\) is our approximation of the truncation error as our estimate for \(y_{i+1}\) is fourth-order and \(z_{i+1}\) is the fifth-order estimate. If \(\mathrm{TE} \geq \epsilon\), then we rescale \(h\) using \(h=h\cdot s\) and repeat the approximation again. If not, then we accept our approximation to the next \(y\) value and rescale \(h\) using \(h=h\cdot s\). This method is very efficient and is the numerical technique I use for integrating ordinary differential equations in all of my JavaScript-based ordinary differential equations solver webpages. Runge-Kutta-Fehlberg fourth/fifth-order method solution to $y'=y, y(0)=1$.
using DataFrames
a = 0.0;
b = 1.0;
N = 5;
h = (b-a)/N;
atol = 1e-5;
max_factor = 5;
function f(x, y)
return y;
end
x = [a];
yRKF45 = [1.0];
error = [0.0];
while x[end] < b
xi = x[end];
yi = yRKF45[end];
# Prevent overshooting the endpoint
hs = min(h, b-xi);
# Runge-Kutta-Fehlberg coefficients
k1 = hs*f(xi, yi);
k2 = hs*f(xi + hs/4,
yi + k1/4);
k3 = hs*f(xi + 3hs/8,
yi + 3k1/32 + 9k2/32);
k4 = hs*f(xi + 12hs/13,
yi + 1932k1/2197 - 7200k2/2197 + 7296k3/2197);
k5 = hs*f(xi + hs,
yi + 439k1/216 - 8k2 + 3680k3/513 - 845k4/4104);
k6 = hs*f(xi + hs/2,
yi - 8k1/27 + 2k2 - 3544k3/2565 +
1859k4/4104 - 11k5/40);
# Fourth-order approximation
y4 = yi + 25k1/216 + 1408k3/2565 +
2197k4/4104 - k5/5;
# Fifth-order approximation
y5 = yi + 16k1/135 + 6656k3/12825 +
28561k4/56430 - 9k5/50 + 2k6/55;
# Error estimation
err = abs(y5-y4);
# Accept or reject the step
if err < atol
push!(x, xi+hs)
push!(yRKF45, y5)
push!(error, err)
end
# Adjust the step size
if err == 0
s = max_factor;
else
s = (atol/(2*err))^(1/5);
end
global h = h*s
if h < eps(max(abs(xi), 1.0))
Base.error("Step size became too small.")
end
end
df = DataFrame(
x = x,
RKF45 = yRKF45,
Exact = exp.(x),
Error = error
);
show(stdout, MIME("text/plain"), df)
println()
As you can see RKF45 achieved more accuracy than both Euler's method and the Runge-Kutta fourth-order method, while using an, on average, larger step size. Also notice how we set the error tolerance of \(10^{-5}\) and none of our errors exceeded this threshold. This is not always the case, however, as this error tolerance is purely local. This means that it is the maximum error we are willing to accept in each individual step of our solution. As these errors accumulate over multiple steps, it is possible for our solution to eventually deviate enough from the exact solution to exceed this threshold.
Its main drawback is that because it is an adaptive method, the number of steps is unknown until you actually compute the solution and this can make implementation in code a little more challenging. As instead of dealing with vectors or arrays (containing your solution) of a set, predictable size, you will need to append new entries to the end of your solution vector/array at each step.
Further, the adaptive stepsize means that if you were hoping for an evenly spaced set of \(x\) values, you may be disappointed by this method. That being said, it is straight forward to fix this issue as you can use interpolation to find the \(y\) values on an evenly spaced \(x\) grid.
An interesting feature of higher-order ODEs is that we can rewrite them as a coupled system of first-order ODEs. Say, for instance, have the second-order ODE:
\[\begin{aligned} y'' = -y. \end{aligned}\]
Cosine and sine functions both satisfy this equation. The solution would be:
\[\begin{aligned} y &= C_1 \cos{x} + C_2 \sin{x}. \end{aligned}\]
So we would need two conditions to uniquely determine \(y\). We could rewrite our second-order ODE as the system:
\[\begin{aligned} u &= y' \\ u' &= -y. \end{aligned}\]
How would we numerically integrate this system? We could apply RKF45 to determine \(y_{i+1}\) (where \(y_0\) and \(y'_0\) will be our initial conditions) using this scheme:
I should clarify that we are maximizing over the error estimates in our two functions \(u\) and \(y\) to calculate \(\mathrm{TE}\). So whichever error estimate is bigger out of those for \(u\) and \(y\), we choose for \(\mathrm{TE}\). If \(\mathrm{TE} < \epsilon\), we continue onto the next step with our new \(y_i\) being the old \(y_{5,i+1}\) and the new \(u_i\) being the old \(u_{5,i+1}\) and obtain our new \(h\) by multiplying it by \(s\). If \(\mathrm{TE} \geq \epsilon\), we multiply \(h\) by \(s\) and repeat the above calculations again.
So we will use the initial conditions \(y(0)=0\) and \(y'(0)=1\). This gives the solution \(y(x)=\sin{x}\) and integrate our ordinary differential equation on the interval \(x\in [0, 2\pi]\).
Runge-Kutta-Fehlberg 4/5th-order method solution to $y''=-y$ with $y(0)=0$ and $y'(0)=1$
using DataFrames
a = 0.0;
b = 2pi;
N = 5;
h = (b-a)/N;
epsilon = 1e-8;
# Initial conditions
x = [a];
y = [0.0];
u = [1.0];
while x[end] < b
xn = x[end];
yn = y[end];
un = u[end];
# Prevent overshooting the endpoint
hs = min(h, b-xn);
# Fehlberg coefficients
k1 = hs*un;
l1 = -hs*yn;
k2 = hs*(un + l1/4);
l2 = -hs*(yn + k1/4);
k3 = hs*(un + 3l1/32 + 9l2/32);
l3 = -hs*(yn + 3k1/32 + 9k2/32);
k4 = hs*(un + 1932l1/2197 - 7200l2/2197 +
7296l3/2197);
l4 = -hs*(yn + 1932k1/2197 - 7200k2/2197 +
7296k3/2197);
k5 = hs*(un + 439l1/216 - 8l2 +
3680l3/513 - 845l4/4104);
l5 = -hs*(yn + 439k1/216 - 8k2 +
3680k3/513 - 845k4/4104);
k6 = hs*(un - 8l1/27 + 2l2 - 3544l3/2565 +
1859l4/4104 - 11l5/40);
l6 = -hs*(yn - 8k1/27 + 2k2 - 3544k3/2565 +
1859k4/4104 - 11k5/40);
# Fourth-order approximations
y4 = yn + 25k1/216 + 1408k3/2565 +
2197k4/4104 - k5/5;
u4 = un + 25l1/216 + 1408l3/2565 +
2197l4/4104 - l5/5;
# Fifth-order approximations
y5 = yn + 16k1/135 + 6656k3/12825 +
28561k4/56430 - 9k5/50 + 2k6/55;
u5 = un + 16l1/135 + 6656l3/12825 +
28561l4/56430 - 9l5/50 + 2l6/55;
# Truncation error estimate
TE = max(abs(y5-y4), abs(u5-u4));
# Step-size adjustment
s = TE == 0 ? 5.0 : (epsilon/(2TE))^(1/5);
# Accept or reject the step
if TE < epsilon
xn_new = xn + hs;
if hs == b-xn
xn_new = b;
end
push!(x, xn_new);
push!(y, y5);
push!(u, u5);
end
# Update step size
global h = hs*s;
if h <= eps(Float64)*max(1.0, abs(xn))
error("Step size became too small.")
end
end
# Exact solutions
y_exact = sin.(x);
u_exact = cos.(x);
# Absolute errors
error_y = abs.(y-y_exact);
error_u = abs.(u-u_exact);
# Construct table
df = DataFrame(
:x => x,
:y => y,
Symbol("y'") => u,
:y_exact => y_exact,
Symbol("y'_exact") => u_exact,
:error_y => error_y,
Symbol("error_y'") => error_u
);
show(stdout, MIME("text/plain"), df)
println()
In Code Listing , we used \(\epsilon=10^{-8}\) as our error tolerance. You may notice that our maximum errors in the output table do indeed exceed this. This is possible as our truncation error estimate is solely for that step, it is not the cumulative error for all steps up until the point we are in our calculation.
So far I have covered how we can numerically integrate initial value problems. Solving boundary value problems and other ODEs without initial conditions is often more challenging, and we usually need to construct and solve matrix equations instead. The finite difference method, for example, involves discretizing our grid into a discrete set of equally-spaced points \(\{x_i\}\) where \(i \in \{0,1,2,...,n\}\). We will call the spacing between points \(h\), which is our step size. Hence we can define our grid points as:
If we call the subject of our ODE, \(u(x)\), then what we do is rewrite the derivatives of \(u\) at each grid point in our ODE in terms of the grid-point values of \(u\). These derivative approximations are based on Taylor series expansions of \(u(x)\) around the grid points. We also construct equations for the grid point values to impose our boundary/other conditions. Then we solve the resulting system of algebraic equations for the grid point values of \(u\).
For instance, if we had the equation \(y''=-y\) and \(y(0)=y(2\pi)=1\) (which implies \(y(x)=\cos{x}\)), we would define \(x_0\) as the start of our domain, which for our ODE is \(0\). If we divide our domain into \(n+1\) equally spaced points then \(h=\dfrac{2\pi}{n}\). Hence:
\[\begin{aligned} x_i &= hi \\ &= \dfrac{2\pi i}{n}. \end{aligned}\]
Let \(y_i\) denote \(y(x_i)\). Then using the Taylor series expansion at \(a=x_i\):
Now we need to explain what \(\mathcal{O}(h^4)\) is. It essentially refers to terms proportional to \(h^4\) and higher powers of \(h\). The reason they did not cancel out when we calculated \(y_{i+1}-y_{i-1}\) is because they would differ between \(y_{i+1}\) and \(y_{i-1}\). Hence we can approximate \(y'_i\) as:
If we add \(y_{i+1}\) and \(y_{i-1}\), we should cancel out the \(y'_i h\) and \(\dfrac{y'''_i}{6} h^3\) terms. To get rid of \(y_i\), we will subtract \(2y_i\):
Hence we have estimates for both \(y''_i\) and \(y'_i\) that have local truncation errors of \(\mathcal{O}(h^2)\). Consequently, they are second-order estimates for \(y''_i\) and \(y'_i\), respectively. Substituting into our differential equation, ignoring the \(\mathcal{O}(h^2)\) yields and adding our boundary conditions:
Code Listing contains code for implementing the finite difference method for our ODE. Implementation of a second-order finite difference method for solving $y''=-y$ with $y(0)=y(2\pi)=1$.
using LinearAlgebra, DataFrames
N = 20
h = 2π / N
d = vcat(1.0, fill(-2 + h^2, N - 1), 1.0)
dl = vcat(ones(N - 1), 0.0)
du = vcat(0.0, ones(N - 1))
A = Tridiagonal(dl, d, du)
b = zeros(N + 1)
b[1] = 1
b[end] = 1
x = LinRange(0, 2pi, N+1);
y = A \ b
yex = cos.(x);
df = DataFrame(x=x, Approximation=y, Exact=yex, Error=abs.(y.-yex))
show(stdout, MIME("text/plain"), df)
println()
As we can see from the below output, our implementation of the finite difference method is rather inaccurate. Higher order approximations for the derivative can be achieved by using more grid point values at each step, but this does make the matrices more complex.
In Code Listing , we implemented a general method for determining the coefficients in a specified order finite difference estimate of a given order derivative (LeVeque, 2007, p. 11).
Implementation of the tenth-order finite difference method for $y''=-y$, $y(0)=y(2\pi)=1$.
using LinearAlgebra
using SparseArrays
using DataFrames
# Generate finite-difference weights using polynomial moments.
function fdweights(offsets, m)
s = length(offsets)
V = BigFloat[
BigFloat(offsets[j])^(k-1)/factorial(k-1)
for k in 1:s, j in 1:s
]
rhs = zeros(BigFloat, s)
rhs[m+1] = 1
return Float64.(V \ rhs)
end
function solve_problem(N)
h = 2π / N
A = spzeros(N+1, N+1)
b = zeros(N+1)
# Dirichlet boundary conditions
A[1, 1] = 1
A[end, end] = 1
b[1] = 1
b[end] = 1
# Interior finite-difference equations:
# y'' + y = 0
for i in 1:N-1
# Select 12 grid points.
# The stencil is shifted near the boundaries.
start = clamp(i-5, 0, N-11)
indices = collect(start:start+11)
offsets = indices .- i
weights = fdweights(offsets, 2)
# Approximate h² y'' + h² y = 0
A[i+1, start+1:start+12] .= weights
A[i+1, i+1] += h^2
end
x = collect(LinRange(0, 2π, N+1))
# Solve the discretised system
y = A \ b
return x, y, A
end
# Calculate a numerical solution
N = 20
x, y, A = solve_problem(N)
# Compare with cos(x), one possible exact solution
y_exact = cos.(x)
df = DataFrame(
x = x,
Approximation = y,
Exact = y_exact,
Error = abs.(y .- y_exact)
)
show(stdout, MIME("text/plain"), df)
println("\nMaximum difference from cos(x): ",
maximum(abs.(y .- y_exact)))
As you can see from Code Listing , I tried implementing higher-order finite difference estimates of the solution and an interesting trend emerged. My matrices became increasingly poorly conditioned. For the tenth-order scheme, for instance, we obtained a condition number of \(6.11\times 10^{10}\). To put this into perspective, the fourth-order method's condition number was \(1.51\times 10^6\). The second-order method's condition number was a mere 4,838.
It is important to note, however, that so far we have only applied the finite difference method to linear differential equations and this is for good reason. When we try to apply it to nonlinear differential equations, we get a nonlinear system of algebraic equations which are much more challenging to solve. There are ways around this, for instance we can use Newton's method to solve the algebraic equation system that arises, and we can also try linearizing our differential equation using a technique known as the Newton-Kantorovich method (Boyd, 2000, p. 526-535). Each of these presents its own challenges though.
Sturm-Liouville problems also give rise to infinite sets of orthogonal functions that are useful when numerically approximating the solution to other differential equations (Boyd, 2000, p. 66-67). If \(\{\phi_i\}\), \(i\in \{0,1,2,...\}\) is our orthogonal function set, we assume our solution, \(u\), to some ordinary differential equation can be written as:
Methods that approximate the solution to a differential equation over the entire domain of the problem using a single sum of basis functions whose number of terms is equal to the number of grid points like this are called spectral methods.
After we write our solution as Equation (34), we discretize our grid into points \(x_i\) (\(i \in \{0, 1, 2,...,n\}\)) and truncate the above series expansion to \(j\in \{0, 1, 2, ..., n\}\). What we do next depends on the precise method we are using.
The simplest spectral method we can use is called the collocation method. It involves writing a matrix equation for \(\mathbf{a}\) (a vector containing \(a_j\), the series coefficients) by enforcing that the differential equation holds exactly at an equal number of grid points to the number of terms in our series expansion, \(n+1\). Then this equation would be:
Where \(\mathbf{A}\) would be a square matrix containing values of \(T_j\) and other functions that multiply our series coefficients when we substitute Equation (34) into our differential equation. \(\mathbf{b}\) would contain any terms in our differential equation that does not involve our series coefficients.
We can rewrite Equation (35) in terms of the grid point values of our solution instead of the series coefficients. Let \(\boldsymbol{\phi}\) be a matrix containing \(\phi_j(x_i)\) and \(\mathbf{u}\) be a vector of \(u(x_i)\) values. Then we can write:
Why do we choose orthogonal function sets as our basis set for spectral methods? Well, orthogonality means our basis functions will be very different to one another and we want our basis functions to be as different from one another as possible to ensure that they can, as accurately as possible, represent all the variation in our solution.
After all, think about it. If we use basis functions that are very similar to each other, how can they possibly represent all the possible variation in our solution? Say, for instance, we used the basis set \(\{\phi_i\}=\{x, 2x, 3x, 4x, ...\}\). This basis set would only be able to account for linear variation in our solution. If our solution has any curvature to it, or turning points, this basis set will be completely inadequate. Further, without any constant term in the basis set, we will not be able to account for vertical translations (that is, shifts up and down by a constant number). Our solution will be forced to go through the origin due to this inability to account for vertical translations.
Maximizing the difference between our basis functions by choosing an orthogonal basis set helps spectral methods often achieve exponential convergence instead of polynomial convergence.
What does exponential and polynomial convergence mean? Remember how the truncation error for Euler's method, Runge-Kutta methods, Runge-Kutta-Fehlberg method, finite difference method, etc. were all of the form \(\mathcal{O}(h^k)\) where \(k\) is some fixed number that depends on the precise method used and \(h\) is the step size? Well, this is what we call polynomial convergence.
Let us switch to using \(n\), where \(n+1\) is our number of grid points (including the endpoints of our domain), to describe the truncation error. Why? Because spectral methods typically do not involve a fixed step size, instead we use \(n+1\) grid points specific to our orthogonal basis set. For instance, if using Chebyshev spectral methods, we often use the set of grid values that extremize the \(n\)th Chebyshev polynomial of the first kind.
As \(h \propto n^{-1}\), we can rewrite our polynomial truncation error as \(\mathcal{O}(n^{-k})\). Spectral methods, however, can have a truncation error of \(O(e^{-qn^{r}})\) where \(q>0\) and \(r>0\) (Boyd, 2000, p. 25).
As we can represent our spectral method solution to a differential equation as a function (the sum in Equation (34)) that approximates the true solution, spectral methods are sometimes called semi-analytical methods instead of true numerical methods. This is because true numerical methods only give us approximated values of our solution.
Personally, I question this distinction as with true numerical solutions we can always approximate the value of our solution at other points by fitting interpolating functions such as splines. Further, spectral methods can be formulated to solve for grid point values of our solution instead of the coefficients of its series expansion, which somewhat eliminates this distinction between spectral methods and true numerical methods.
If we instead split the domain up into smaller sections with a separate function of the form Equation (34) defined on each, then we are said to be using a spectral element method. Finite element methods are very similar as they do split the domain up and define a series-based solution on each part of the domain. The difference is that the series usually has fewer terms and achieves lower accuracy than their spectral element counterparts.
Like with the finite difference method, spectral methods, spectral element methods and finite element methods are also easiest applied to linear differential equations. This is because they result in a system of equations — if the differential equation is linear, this system is linear, but if not the system is nonlinear, which requires the application of Newton's method. Either that or we can linearize our differential equation using the Newton-Kantorovich method.
So far we have discussed collocation-based spectral methods. In these methods, we formulate our differential equation as a system of simultaneous equations that arise from enforcing that our differential equation holds at every grid point. There are other spectral methods out there, some of which are based on the Galerkin method. In the Galerkin method, we rewrite our differential equation so that one side of it is zero. Then we compute the inner product between our rewritten differential equation and a test function (which is usually a member of our orthogonal basis set) and set this to zero. We may also simplify this inner product using integration by parts.
Many different orthogonal functions can be used when applying spectral methods. Among the most popular are Chebyshev polynomials of the first kind and Fourier series functions. Chebyshev polynomials of the first kind, \(T_i(x)\), are defined on \(x\in [-1,1]\) as:
I would imagine that you are looking at Equation (37) and wondering, how can \(T_j\) be a polynomial when it is defined in terms of cosine and its inverse? Say \(j=0\), we get:
This pattern continues on from here, too. Further, this is just one way to define Chebyshev polynomials of the first kind and is the most convenient way for when you are using them to approximate the solution to differential equations. That being said, they can also be defined using a recursion relation that makes the fact that they are polynomials all the more clear. Specifically this is the recursion relation (Boyd, 2000, p. 323):
These points extremize the \(n\)th Chebyshev polynomial of the first kind and this makes the matrices we get easier to work with, as these matrices will be better conditioned (that is, have a condition number close to one).
Interestingly, \(\dfrac{\sin{j\cos^{-1}{x}}}{\sqrt{1-x^2}}\) has a name, it is \(U_{j-1}(x)\) where \(U_{j-1}\) denotes the \(j-1\)th Chebyshev polynomial of the second kind. It is important to note that this formula is undefined at \(x=\pm 1\); at these end points we have this identity (Boyd, 2000, p. 497):
I should mention that while our basis functions are limited to \(x\in [-1,1]\), this does not mean we are limited to \(x\in[-1,1]\) for the differential equations we can solve. As we can apply any number of different transformations to transform \(x_i\) from \([-1,1]\) to other domains. The most straight-forward is a linear transformation. Say we want to transform to \(y\in [a,b]\) we would use:
\[\begin{aligned} y &= \dfrac{b-a}{2}x + \dfrac{b+a}{2}. \end{aligned}\]
We can also define a differentiation matrix. If \(\mathbf{dT} = (T'_j(x_i))\) and \(\mathbf{T}=(T_j(x_i))\) we can define the differentiation matrix:
This matrix, when run on a vector of function values at \(x_i\) computes its first derivative. If you multiply the vector by \(\mathbf{D}\) twice, you will get the second derivative. Let \(\mathbf{D}^{(2)}\) represent the second derivative matrix; it will equal \(\mathbf{D}^2=\mathbf{D}\mathbf{D}\). It can also be calculated using \(\mathbf{d^2T}=(T''_j(x_i))\) as \(\mathbf{D}^{(2)}=\mathbf{d^2T}\mathbf{T}^{-1}\). Luckily, there are also more efficient ways of calculating \(\mathbf{D}\), such as using (where \(\mathbf{D}=(D_{ij})\)) (Trefethen, 2000, p. 53):
Where \(\mathrm{Ai}(x)\) and \(\mathrm{Bi}(x)\) are Airy functions, which are actually defined as the solution to this exact ODE. Say we have the boundary conditions \(u(0)=\mathrm{Ai}(0)\) and \(u(\infty)=0\). Then the solution would be \(u(x)=\mathrm{Ai}(x)\). This is because:
Then to transform our grid points from \([-1,1]\) to \([0,\infty]\) we will use the transformation (where \(y\) are our Chebyshev grid points and \(x\) is our semi-infinite domain grid points):
\[\begin{aligned} x &= L \dfrac{1+y}{1-y}. \end{aligned}\]
Where \(L\) is a parameter we might need to fine tune to get the best approximation. Hence:
\(\mathbf{D}_x\) is the differentiation matrix with respect to \(x\) and \(\mathbf{D}_y\) is the differentiation matrix with respect to \(y\). \(\mathbf{Diag}\left(\dfrac{(1-y_i)^2}{2L}\right)\) represents a matrix with \(\dfrac{(1-y_i)^2}{2L}\) on its diagonal and \(0\) in all other entries. To clarify what I mean, I will show you what this matrix looks like:
Why do we left-multiply \(\mathbf{D}_y\) by this matrix? Well, if you manually calculate the matrix product between these matrices you will find that each row of \(\mathbf{D}_y\) (which corresponds to a different value of \(y_i\)) is multiplied by the corresponding value of \(\dfrac{(1-y_i)^2}{2L}\). This is the matrix analogue to our expression for \(\dfrac{d}{dx}\) in terms of \(y\).
Where \(\mathbf{0}\) denotes a column vector of just zeros. Although, we will need to remove two rows from this matrix equation and replace them with rows to impose our boundary conditions. Say these rows are rows 1 and \(n+1\), which correspond to \(x_0\) and \(x_n\). Say we call \(\mathbf{A}=\mathbf{D}_x^2 - \mathbf{Diag}{(x_j)}\). Then the edits we make to impose our boundary conditions will be setting \(A_{1,1} = 1\) and all remaining entries in the first row of \(\mathbf{A}\) will be \(0\). As for \(A_{n+1,n+1}=1\) and all other entries in the \(n+1\)th row of \(\mathbf{A}\) will be zero.
Code Listing was used to solve our Airy equation ODE.
Solution to the Airy equation via Chebyshev spectral method.
using LinearAlgebra, SpecialFunctions, DataFrames
# Parameters
n = 40
L = 10.0
# Chebyshev extrema
y = -cos.(π .* (0:n) ./ n)
# Chebyshev differentiation matrix
c = [2.0; ones(n-1); 2.0] .* (-1.0).^(0:n)
X = repeat(y, 1, n+1)
dX = X - X'
# This is the i!=j part of the differentiation matrix.
D = (c * (1 ./ c)') ./ (dX + I)
# This imposes that the sum of each row of D = 0, that way D*constant=0
D -= Diagonal(vec(sum(D, dims=2)))
# Transformation to the semi-infinite domain
x = L*(y.+1)./(-y.+1)
# Derivative transformation
q = (1 .- y).^2 ./ (2L)
# Second derivative matrix
D2 = Diagonal(q) * D * Diagonal(q) * D
# Collocation matrix: y'' - xy = 0
A = copy(D2)-diagm(x);
# Boundary conditions
A[1,:] .= 0
A[1,1] = 1
A[end,:] .= 0
A[end,end] = 1
# Right-hand side: y(0) = Ai(0), y(∞) = 0
b = zeros(n+1)
b[1] = airyai(0)
# Solve
u = A \ b
# Chebyshev coefficients
V = [cos((j-1)*acos(y[i])) for i in 1:n+1, j in 1:n+1]
a = V \ u
# Exact solution
uexact = [i == n+1 || x[i] > 100 ? 0.0 :
airyai(x[i])
for i in 1:n+1]
# Results
df = DataFrame(
y = y,
x = x,
Approximation = u,
Exact = uexact,
Error = abs.(u .- uexact)
)
show(stdout, MIME("text/plain"), df)
println()
println("\nMaximum absolute error: ", maximum(abs.(u .- uexact)))
The condition number of our matrix \(\mathrm{A}\) (\(=\mathbf{D}_x^2 - \mathbf{Diag}{(x_i)}\)) was 15,522.6. Which is much smaller than the matrices we obtained for the fourth and tenth-order finite difference method.
Code Listing was used to implement the Galerkin method for solving Equation (38). In this method, we use the test function \(v_j=(1-y^2)T_j(y)\) where \(j=0,1,2,3,...,n-2\). Why the \(1-y^2\) factor? Interestingly, it improves the condition number of the matrix we get. We will cover how later. Why only up to \(n-2\)? With our transformation, our Equation (38) becomes, in terms of \(y\):
An important question arises from Equation (39): how do we calculate the integrals involved? Well, this is where we apply Chebyshev-Gauss quadrature. Chebyshev-Gauss quadrature is a type of Gaussian quadrature, which are schemes for numerically integrating functions using techniques that are exact for polynomials of degree \(2n-1\) or below. In Chebyshev-Gauss quadrature, we apply the formula:
\[\begin{aligned} \int_{-1}^1 \dfrac{f(y)}{\sqrt{1-y^2}} dy &\approx \dfrac{\pi}{n}\sum_{i=1}^n f(y_i). \end{aligned}\]
Where \(y_i\) are the zeros of the \(n\)th Chebyshev polynomial of the first kind. These zeros are given by:
This brings us to why there is a factor of \(1-y^2\) in our test functions. Due to how we have transformed our problem from \(y\in [-1,1]\) to \(x\in [0,\infty)\), combined with our weight function being \(\dfrac{1}{\sqrt{1-y^2}}\) we have singularities at the endpoints (points where our integrand becomes undefined), so it is useful to address these singularities by multiplying by \(1-y^2\) (which is zero at the endpoints). Hence:
#!/usr/bin/env julia
"""
Chebyshev weighted-residual solution of
u''(x) - x*u(x) = 0, x ∈ [0, ∞),
u(0) = Ai(0), u(∞) = 0.
The rational map x = ℓ(1+t)/(1-t) maps [0,∞] to [-1,1]. The trial
solution is Uₙ(t) = Σ aᵢ Tᵢ(t). The two boundary conditions are imposed
strongly, while the residual is orthogonal to the Chebyshev polynomials
Tⱼ(t), j = 0, …, n-2, in the Chebyshev inner product.
Requires SpecialFunctions.jl for `airyai` (only used to set Ai(0) and to
report an error against the exact solution).
"""
using LinearAlgebra
using SpecialFunctions
"""Values of Tₖ(t), Tₖ'(t), and Tₖ''(t), for k = 0, …, n."""
function chebyshev_tables(t::Float64, n::Int)
T = zeros(n + 1)
dT = zeros(n + 1)
ddT = zeros(n + 1)
T[1] = 1.0
if n >= 1
T[2] = t
dT[2] = 1.0
end
for k in 2:n
# Array index k+1 corresponds to polynomial degree k.
T[k + 1] = 2t * T[k] - T[k - 1]
dT[k + 1] = 2T[k] + 2t * dT[k] - dT[k - 1]
ddT[k + 1] = 4dT[k] + 2t * ddT[k] - ddT[k - 1]
end
return T, dT, ddT
end
"""Evaluate Σₖ a[k+1]Tₖ(t) by Clenshaw recurrence."""
function chebyshev_value(a::AbstractVector, t::Real)
bkp1 = zero(eltype(a))
bkp2 = zero(eltype(a))
for k in length(a):-1:2
bk = 2t * bkp1 - bkp2 + a[k]
bkp2, bkp1 = bkp1, bk
end
return a[1] + t * bkp1 - bkp2
end
"""
airy_galerkin(n=32; L=2.0, quadrature_points=max(64, 2n + 8))
Solve for the n+1 Chebyshev coefficients. `L` sets the scale of the
rational compactification; values near the region in which the solution
changes appreciably (order one here) work well.
"""
function airy_galerkin(n::Int = 40; L::Float64 = 10.0,
quadrature_points::Int = max(64, 2n + 8))
n >= 2 || throw(ArgumentError("n must be at least 2"))
L > 0 || throw(ArgumentError("L must be positive"))
quadrature_points >= n + 2 || throw(ArgumentError(
"need at least n + 2 Gauss--Chebyshev points"))
# A[j+1, i+1] = <T_j|L[T_i]>, j=0,…,n-2.
A = zeros(n - 1, n + 1)
# Calculate A_{i,j} using Chebyshev-Gauss quadrature
for q in 1:quadrature_points
θ = (q - 0.5) * pi / quadrature_points
t = cos(θ)
weight = pi / quadrature_points
T, dT, ddT = chebyshev_tables(t, n)
# Op is the transformed, polynomial-coefficient differential operator
OpT = 1/4L^2*(1 - t)^4 .* ddT .-
1/2L^2 * (1 - t)^3 .* dT .-
L * (1 + t)/(1-t) .* T
for j in 0:(n - 2)
test = (1-t^2)*T[j + 1]
@views A[j + 1, :] .+= weight * test .* OpT
end
end
# Append U(-1)=Ai(0) and U(1)=0 to make an (n+1) × (n+1) system.
system = Matrix{Float64}(undef, n + 1, n + 1)
system[1:n-1, :] .= A
system[n, :] .= [(-1.0)^k for k in 0:n]
system[n + 1, :] .= 1.0
rhs = vcat(zeros(n - 1), airyai(0.0), 0.0)
coefficients = system \ rhs
println("Condition number = ", cond(Matrix(system)))
return (; coefficients, L, n, quadrature_points)
end
"""Evaluate the rational-Chebyshev approximation at x ≥ 0."""
function value(solution, x::Real)
x >= 0 || throw(ArgumentError("x must be non-negative"))
t = isinf(x) ? 1.0 : (x - solution.L) / (x + solution.L)
return chebyshev_value(solution.coefficients, t)
end
function report(solution)
points = (0.0, 0.5, 1.0, 2.0, 4.0, 8.0, 12.0)
println("n = ", solution.n, ", L = ", solution.L,
", quadrature points = ", solution.quadrature_points)
println("\n x Galerkin u(x) Ai(x) absolute error")
for x in points
numerical = value(solution, x)
exact = airyai(x)
println(rpad(string(x), 8), " ",
lpad(string(round(numerical, sigdigits=11)), 18), " ",
lpad(string(round(exact, sigdigits=11)), 14), " ",
abs(numerical - exact))
end
grid = range(0.0, 12.0; length=1001)
max_error = maximum(abs(value(solution, x) - airyai(x)) for x in grid)
left_bc_error = abs(value(solution, 0.0) - airyai(0.0))
right_bc_error = abs(value(solution, Inf))
println("\nmax error on [0,12]: ", max_error)
println("boundary residuals: |u(0)-Ai(0)| = ", left_bc_error,
", |u(∞)| = ", right_bc_error)
end
solution = airy_galerkin()
report(solution)
As we can see from the above output, \(\mathbf{A}\) has a condition number of about 70. When I opted for \(v_j(y)=T_j(y)\), the condition number was about \(5.6\times 10^6\). As for \(v_j=(1-y)T_j(y)\) (which just addresses the \(y=1\) and \(x=\infty\) singularity) it gave the condition number of \(33,575.5\). Which suggests that \(v_j(y)=(1-y^2)T_j(y)\) is optimal from a numerical stability perspective.
An important issue I should probably address is how do we solve Sturm-Liouville and other differential equations with eigenvalues? Well, the answer is that we construct an eigenvector equation of the form:
Where \(\mathbf{u}\) is our vector of values of our function at our grid values and \(\mathbf{R}=\mathbf{Diag}(r(x_i))\). These eigenvalue matrix problems can be solved by first multiplying by \(\mathbf{R}^{-1}\) before applying the techniques previously mentioned. Typically, we omit the endpoints from our matrices to impose our boundary conditions when those boundary conditions are of the form \(u(a)=u(b)=0\). We can impose other boundary conditions by including them in the first and final row of our matrix and if they are zero, the corresponding rows of \(\mathbf{R}\) should be zero, too.
Then we use established techniques for finding eigenvalues and eigenvectors of matrices. We can construct such an equation when we apply finite difference, spectral, finite element and spectral element methods to our linear eigenvalue differential equation problem.
Only \(\mathrm{Ai}(x)\) goes to \(0\) as \(x\rightarrow\infty\). Its derivative also goes to \(0\) in this limit. Imposing our other boundary condition, \(u'(0)=0\), yields:
We denote the Fourier transform of a specified function as \(\mathcal{F}(f)\). It has broad applications, including in signal processing (as it identifies frequencies present in sounds) and in solving differential equations. This latter use is the result of the relationship between \(\mathcal{F}(f^{(m)})\) and \(f\) being a simple multiplication by \((ik)^m\).
It also has a discrete counterpart called the discrete Fourier transform (DFT). If you have a sequence of numbers corresponding to your values of \(f(x)\) at \(\{x_j\}=\{h, 2h, 3h, ..., 2\pi\}\) and \(k\in \{-\frac{n}{2}+1, -\dfrac{n}{2}+2, -\dfrac{n}{2}+3, ..., \frac{n}{2}\}\) where \(h=\dfrac{2\pi}{n}\) (Trefethen, 2000, p. 18), the discrete Fourier transform yields (Trefethen, 2000, p. 18):
The fast Fourier transform (FFT) is an especially efficient implementation of the discrete Fourier transform. This simply means that when you compute it, say in a programming language like Julia, it runs faster than you might otherwise expect while still returning the correct result. The DFT of the \(m\)th derivative of \(f\) should be \((ik)^m\hat{f}_k\), except when \(k=\frac{n}{2}\) and \(m\) is odd in which case it would be \(0\) (Trefethen, 2000, p. 23).
The methods for numerically integrating partial differential equations (PDEs) tend to be more complex than those for solving ODEs due to the added complexity of needing to work with more than one independent variable. The finite difference, finite element, spectral and spectral element methods can be applied directly to PDEs, especially linear PDEs. Although the matrices become more complex when we add additional independent variables. Further, some of the other methods used to numerically integrate PDEs utilize ODE methods in some way. For instance, the code in Code Listing solves the heat equation by approximating spatial derivatives using the fast Fourier transform and its inverse and then integrates on time using RKF45.
When we have a nonlinear differential equation and we apply a finite difference method, finite element method, spectral element method or spectral method to solve it, we obtain a nonlinear system of equations. We could solve this using Newton's method, or alternatively we could first linearize our differential equation to avoid the need to use Newton's method. This linearization approach is called the Newton-Kantorovich method.
Linearizing differential equations can be achieved by essentially using the first two terms (the constant term and linear term) of the differential equation's Taylor series. Specifically, we expand around our \(n\)th approximation to the solution to our differential equation. As an example, consider Equation (53). We will later encounter this differential equation when we study the problem of the simple pendulum. We would define:
Where \(\Delta\) will be the subject of our linearized differential equation and \(\theta_n\) is our \(n\)th approximation of \(\theta\). Substituting this into Equation (53) and expanding the nonlinear term in terms of the first two terms of its Taylor series about \(a=\theta_n\) yields:
We will use the Chebyshev collocation method to solve this for \(\Delta\). We will use a linear transformation of \(x\in[-1,1]\) to \(t\in [0,T]\) (where \(T\) is the period of our problem). Specifically:
\[\begin{aligned} t &= \dfrac{T}{2}(x+1). \end{aligned}\]
Why? Because then \(\theta_{n+1}\) should automatically satisfy the initial conditions. An important question to answer is what should be our first guess as to the solution? In the Newton-Kantorovich method, the first guess matters a lot. A poor first guess can lead to the method failing to converge, which means we will not actually get a solution. We know, from our solution in the Without air resistance section, that the simple pendulum under these initial conditions goes to a minimum angle of \(-\pi\) and maximum angle of \(0\). The curve looks roughly like a cosine wave, too. A decent first guess might be:
How would we determine \(T\)? We can use Equation (126). Ignoring \(\beta\) (which is a product of the indefinite nature of the integral), making our integral definite from \(-\pi\) to \(0\) and assuming \(t\) must be positive gives:
\[\begin{aligned} t &= \int_{-\pi}^0 \sqrt{\dfrac{ml^2}{2(E-mgl\sin{\theta})}} d\theta \end{aligned}\]
This should be half our period, as a full period should take us back to \(0\), but we cannot integrate from \(0\) to \(0\) as when the upper and lower bounds are the same, integrals return \(0\). \(\theta(0)=0\) and hence \(V=mgl\sin{\theta}\) should also be zero at \(t=0\). \(\dot{\theta}(0)=0\) would also imply that \(T=\dfrac{ml^2\dot{\theta}^2}{2}\) is zero. Hence the total energy of the system, \(E\), is \(0\). Hence:
\(\Gamma(\frac{1}{2})=\sqrt{\pi}\). \(\Gamma(\frac{1}{4})\) cannot be expressed so succintly but \(\Gamma(\frac{3}{4})=\dfrac{\sqrt{2}\pi}{\Gamma\left(\frac{1}{4}\right)}\). Hence:
\[\begin{aligned} T &= \sqrt{\dfrac{2l}{g}}\dfrac{\sqrt{\pi}\Gamma(\frac{1}{4})}{\dfrac{\sqrt{2}\pi}{\Gamma\left(\frac{1}{4}\right)}} \\ &= \sqrt{\dfrac{l}{g\pi}} \Gamma\left(\dfrac{1}{4}\right)^2. \end{aligned}\]
Code Listing displays the code we used to implement this solution on \(t\in[0, T]\). Script for solving simple pendulum problem with the Newton-Kantorovich method.
using LinearAlgebra, SpecialFunctions
using DataFrames
using Plots, QuadGK, LaTeXStrings
# Parameters
N = 40
gravity = 9.81
l = 1.0
α = gravity / l
# Period
T = sqrt(l / (π*gravity)) * gamma(1/4)^2
tf = T;
# Newton iteration parameters
tol = 1e-12
maxiter = 50
# Chebyshev-Lobatto extrema grid (ascending order)
x = -cos.(π .* (0:N) ./ N)
# Map to the time interval [0, T]
t = (tf / 2) .* (1 .+ x)
# Chebyshev differentiation matrix
c = [2.0; ones(N-1); 2.0] .* (-1.0).^(0:N)
X = repeat(x, 1, N+1)
dX = X - X'
D = (c * (1 ./ c)') ./ (dX + LinearAlgebra.I)
D -= Diagonal(vec(sum(D, dims=2)))
# Differentiation matrices with respect to time
Dt = (2 / tf) .* D
D2t = Dt * Dt
# Initial approximation
θ = -(π / 2) .* (1 .- cos.(2π .* t ./ T) )
# Newton-Kantorovich iteration
let converged = false
for n in 1:maxiter
# Residual of the nonlinear differential equation
F = D2t * θ + α .* cos.(θ)
# Jacobian of the nonlinear system
J = D2t - Diagonal(α .* sin.(θ))
# Right-hand side of Newton correction equation
rhs = -F
# Initial condition: Δ(0) = -θ_n(0)
J[1, :] .= 0.0
J[1, 1] = 1.0
rhs[1] = -θ[1]
# Initial condition: Δ'(0) = -θ_n'(0)
J[2, :] = Dt[1, :]
rhs[2] = -(Dt * θ)[1]
# Solve for the correction
Δ = J \ rhs
# Update approximation
θ .+= Δ
# Check convergence
iteration_error = norm(Δ, Inf)
println("Iteration $n: correction magnitude = $iteration_error")
if iteration_error < tol
converged = true
println("Newton-Kantorovich iteration converged.")
break
end
end
if !converged
@warn "Newton-Kantorovich iteration did not converge."
end
end
# Interpolate solution to grid with more points to make smoothen plot
NN = 1000;
xx = LinRange(-1, 1, NN+1);
tt = T/2*(xx.+1);
n = 0:N
T = cos.(acos.(x) .* n');
TT = cos.(acos.(xx) .* n');
a = T\θ;
θθ = TT*a;
# Plot angular displacement
p1 = plot(
tt, θθ,
xlabel = L"t\ (\mathrm{seconds})",
ylabel = L"\theta",
legend=false,
linewidth = 2
)
savefig(p1, "pendulum_theta.svg")
Newton-Kantorovich solution to the simple pendulum equation.
In this example, we used our knowledge of the problem to determine a viable initial guess. We often do not have this luxury and in this event, we will need to rely on another method. When we have an initial value problem like we did in this case, we can use a method such as Runge-Kutta fourth-order method to provide this initial guess. Alternatively, if we do not have initial conditions but instead have boundary or other conditions, we can try to approximate the corresponding initial conditions and then apply these initial value problem solving methods to get our initial guess. Sometimes we can get away with using a solution to our differential equation that is based on its Taylor series (e.g. Equation (55) for the simple pendulum) as our initial guess.
Lagrangian mechanics is one of four major formulations of classical mechanics with the others being Newtonian mechanics, Hamiltonian mechanics and the Hamilton-Jacobi equation. In Lagrangian mechanics, we define a quantity known as the Lagrangian of our physical system:
\[\begin{align} L &\stackrel{\text{def}}{=} T - V. \tag{42} \end{align}\]
Where \(T\) is kinetic energy and \(V\) is potential energy of our entire physical system. It is important to note that only conservative forces contribute to \(V\). Lagrangian mechanics can account for non-conservative (i.e. dissipative) forces, too, but we will get to how one handles them later.
The distinction between conservative and non-conservative forces is whether they change the net energy of your system. For instance, gravity does not because any increase in kinetic energy it causes is balanced by a corresponding reduction in potential energy. Likewise, any loss of kinetic energy caused by gravity is balanced by an increase in potential energy. Consequently, it is a conservative force. Air resistance, however, is a non-conservative force because the losses it causes in kinetic energy are not balanced by increases in potential energy.
When there are no non-conservative forces, the equations of motion can be derived by first determining our system's Lagrangian and then applying a set of partial differential equations known as the Euler-Lagrange equations to this Lagrangian. The Euler-Lagrange equations are:
\(q_i\) are the \(n\) degrees of freedom (or generalized coordinates) of our problem and \(\dot{q}_i\) are their time derivatives (or the generalized velocities). The \(\dfrac{d}{dt}\) is not a partial derivative and this is purposeful, as when we differentiate \(\dfrac{\partial L}{\partial \dot{q}_i}\) with respect to \(t\), we treat \(q_i\) and \(\dot{q}_i\) as functions of \(t\) and wherever they appear in \(\dfrac{\partial L}{\partial \dot{q}_i}\) we differentiate them against \(t\).
Next, I should explain what "degrees of freedom" are. They are essentially our variables of interest. For simpler problems, the degrees of freedom in our problem are often the spatial dimensions of our problem. For instance, if we were to study an object in free fall and we were to try to simplify our problem as much as possible and not consider any movement in the horizontal directions then \(n\) could be 1 and \(q_1\) would just be the height of the object above ground level.
Likewise, when we study the simple pendulum — which is a problem in which we have an idealized rigid pendulum whose rod has zero mass, zero friction and for which there is absolutely no air resistance — typically we only consider a single degree of freedom, which is the angle our pendulum's rod makes with either the negative \(y\) axis or the positive \(x\) axis, depending on the preferences of whoever is setting up the problem.
Of course, the Euler-Lagrange equations can also be written as:
Which is usually the form I use when I apply them to specific problems as usually the highest order time derivatives will be on the left-hand side of this equation.
The derivation of Equations (43) requires knowledge of a field of mathematics known as the calculus of variations as well as a physics principle known as the stationary action principle. I will provide my own derivation here; although, I would suggest checking out Veritasium's video on this topic as it provides a more accessible introduction to this topic.
There is a quantity known as the action — which is denoted as \(S\) — that is defined as:
\[\begin{align} S &\stackrel{\text{def}}{=} \int_{t_0}^{t_f} L(q_i, \dot{q}_i, t) dt. \tag{45} \end{align}\]
One interesting property of the action is that nature consistently sets it to its stationary point, and this is regardless of context. Regardless of whether we are examining the motion of planets with Newton's second law, or studying the behaviour of black holes with general relativity, or checking out the behaviour of subatomic particles, there is always an action that is at its stationary point. If you would like an explanation for how this arises in classical mechanics, I suggest checking out this excellent video by Dr Jorge S Diaz. Traditionally, this stationary point is typically thought of as a minimum (hence why this is also known as the principle of least action), but strictly speaking it is not always a minimum.
Of all the paths that an object could explore, the one that it actually explores is the one that sets the action to its stationary point. Figure provides some example paths that we examine when applying the principle of stationary action. In the terminology of the calculus of variations, we can express the fact the action is at its stationary point as:
\[\begin{align} \delta S &= 0. \tag{46} \end{align}\]
This is analogous to saying, in regular calculus, that our function's first derivative is zero. Which, as you may remember from your maths classes, is an equation we can solve to find the stationary point(s) of our function. The difference is that \(S\) is not a function that takes some value of an independent variable (e.g. \(x\)) and returns a value, instead \(S\) is a functional. Which means that it takes a function as its input and returns a value. In this case, the function it takes as its input are the \(q_i(t)\) that specify our path. This is what distinguishes calculus of variations from regular calculus. In calculus of variations, we are working with functionals, whereas in regular calculus we are working with functions.
Say we add functions \(\delta q_i\) to \(q_i\), thereby adjusting the path our object takes. Crucially, however, the end times and end points of our path will be unchanged. The new, adjusted action we will denote by \(S'\) and it is:
We will expand \(L\) using the first couple of terms of its Taylor series around \(a=q_i\) and \(a=\dot{q}_i\) (we have multiple \(a\)s as our function depends on multiple variables):
At the end times of our path, \(\delta q_i\) should be zero, as the endpoints are fixed. Hence the term \(\left[\dfrac{\partial L}{\partial \dot{q}_i}\delta q_i\right]_{t_0}^{t_f}\) should evaluate to zero. Our expression then simplifies to:
The first of these terms is present in \(S\), too. Hence:
\[\begin{aligned} S' - S &\approx \int_{t_0}^{t_f}\sum_{i=1}^n\delta q_i \left(\dfrac{\partial L}{\partial q_i} - \dfrac{d}{dt} \dfrac{\partial L}{\partial \dot{q}_i}\right) dt. \end{aligned}\]
We can denote this first-order approximation to how much \(S\) changes as \(\delta S\). It is a first-order approximation as this is the highest power of \(\delta q_i\) and \(\delta \dot{q}_i\) it depends on. First order also describes the highest order derivatives of \(L\) with respect to \(q_i\) and \(\dot{q}_i\) that our approximation depends upon. Hence:
Hence \(\delta S\) will equal zero irrespective of \(\delta q_i\) if and only if Equations (43) hold. Hence from setting \(\delta S=0\) we get the Euler-Lagrange equations.
I guess next I should explain how we account for non-conservative forces. Essentially we replace the \(0\) in Equations (43) with the generalized force \(Q_i\). It is defined as:
Where \(\textbf{F}_j\) represents the vector of the \(j\)th non-conservative force we wish to account for in our equations of motion. As you can see by the summation bounds, we have \(m\) non-conservative forces we wish to account for. \(\textbf{r}_j\) is the position vector for force \(j\). \(\textbf{F}_j\cdot\dfrac{\partial \textbf{r}_j}{\partial q_i}\) denotes the dot product between \(\textbf{F}_j\) and \(\dfrac{\partial \textbf{r}_j}{\partial q_i}\) (which can be called the covariant basis vector). Alternatively, to calculate \(Q_i\) we can use velocities instead of positions:
\(\dot{\textbf{r}}_j\) is the time derivative of the position vector (that is, the velocity vector) for force \(j\). Hence the more generalized form of Equations (43) is:
To apply Equations (43), we will treat it as a simple pendulum with no friction, a massless rod and no air resistance. The pendulum will consist of a rod with a bob at one end and freely rotating around a central point. We will define this central point as being the origin in Cartesian coordinates. Say the rod is of fixed length \(l\) metres. The pendulum bob will be of mass \(m\) kilograms. As you can see in Figure , we have defined \(\theta\) as the angle between the rod and the positive \(x\)-axis going counter-clockwise. Hence the \(x\) and \(y\) coordinates of the pendulum bobs are:
\[\begin{aligned} x &= l\cos{\theta} \\ y &= l\sin{\theta}. \end{aligned}\]
Equation (53) has, as its highest order derivative, a second-order derivative. It also only involves ordinary derivatives (not partial derivatives). Hence it is a second-order ordinary differential equation (ODE). Second-order ODEs are typically obtained in both Newtonian and Lagrangian mechanics. The number of second-order ODEs obtained for a given system depends on the number of degrees of freedom of the system.
Technically speaking it is possible to analytically solve Equation (53), but it requires the use of non-standard functions called elliptic integrals. Another option is we can use the Taylor series around \(a=-\dfrac{\pi}{2}\). Why \(-\dfrac{\pi}{2}\)? Because this corresponds to the pendulum being on the negative \(y\) axis. This is an equilibrium point of the simple pendulum, as if the pendulum has no kinetic energy (in other words \(\dot{\theta}=0\)) when it is at this point, it will stay perfectly still and remain at \(\theta=-\dfrac{\pi}{2}\) forever. So what we want to study with the Taylor series is what happens if we only slightly perturb the pendulum from this equilibrium point, as a slight perturbation from this point should keep \(\cos{\theta}\) well approximated by the first couple of terms of its Taylor series. Okay, so we already know the \(n\)th derivative of \(\cos{\theta}\) with respect to \(\theta\) from the Maclaurin and Taylor series section, it is:
Now we want to make our differential equation as simple as possible, so we will only consider the first term in this Taylor series, the \(n=0\) term. In which case \(\cos{\theta} \approx \theta + \dfrac{\pi}{2}\). Hence Equation (53) becomes:
Where \(C_1\) and \(C_2\) are constants that depend on our initial conditions (similarly to the arbitrary constants of integration you get when using indefinite integrals) and \(C_3\) is a constant we will work out next, right after differentiating \(\theta(t)\) for later use:
\(C_3\) is a constant, so double differentiating it will remove it. Hence we know that \(C_3\) only enters Equation (54) via the \(\theta\) term on the right-hand side. So we need to impose the condition that:
At \(t=0\), let \(\theta = \theta_0\) and \(\dot{\theta}=\dot{\theta}_0\). These values simply represent the initial values of \(\theta\) and \(\dot{\theta}\).
So we can see \(\theta(t)\) is approximated, when it deviates only slightly from \(\theta=-\dfrac{\pi}{2}\), quite well by sine and cosine functions. More generally, we can use numerical techniques to approximate our solution. Below is some Julia code that numerically approximates the solution for \(\theta_0=\dot{\theta}_0=0\), \(g=9.81\mathrm{m}\cdot \mathrm{s}^{-2}\), \(l=1\mathrm{m}\) and \(m=1\mathrm{kg}\). These initial conditions means the pendulum starts stationary on the positive \(x\)-axis. Then gravity pulls it down and up towards the negative \(x\)-axis (at \(\theta=-\pi\)) and then back down and towards the positive \(x\)-axis (\(\theta=0\)) and over and over. Simple pendulum simulation code.
using DifferentialEquations, Plots, LaTeXStrings
ENV["GKSwstype"] = "100"
g, l = 9.81, 1.0
fps = 30
function pendulum!(du, u, p, t)
du[1] = u[2]
du[2] = -(g/l)*cos(u[1])
end
tspan = (0.0, 10.0)
u0 = [0.0, 0.0] # θ₀ = 0, θ̇₀ = 0
prob = ODEProblem(pendulum!, u0, tspan)
sol = solve(prob, saveat=1/fps)
plot(sol.t, sol[1, :], label=false)
xlabel!(L"t\;(\mathrm{seconds})")
ylabel!(L"\theta\;(\mathrm{radians})")
savefig("Simple_pendulum_theta.svg")
# Animate with θ measured counterclockwise from the positive x-axis
x = l .* cos.(sol[1, :])
y = l .* sin.(sol[1, :])
anim = @animate for i in eachindex(sol.t)
plot(
[0, x[i]], [0, y[i]];
xlims=(-1.1l, 1.1l),
ylims=(-1.1l, 1.1l),
aspect_ratio=:equal,
label=false,
xlabel=L"x\ (\mathrm{metres})",
ylabel=L"y\ (\mathrm{metres})",
)
scatter!([x[i]], [y[i]]; markersize=8, label=false)
end
gif(anim, "Simple_pendulum.gif"; fps=fps)
Figure shows the plot of \(\theta\) vs \(t\) produced by Code Listing . Figure contains an animation of the simple pendulum simulated by the above Julia code.
For the sake of simplicity, we will only consider the air resistance experienced by the pendulum bob itself, not by the rod. The air resistance force vector for the pendulum bob would be:
This equation cannot be analytically solved, so numerical solutions are necessary. There is a numerical solver for an even more complex version of the dampened single pendulum here. Below is some Julia code for numerically solving the dampened single pendulum problem with \(\theta_0=0\), \(\dot{\theta}_0=0\), \(g=9.81\mathrm{m}\cdot \mathrm{s}^{-2}\), \(l=1\mathrm{m}\), \(m=1\mathrm{kg}\), \(\rho=2.0 \mathrm{kg}\cdot \mathrm{m}^{-3}\), \(C_D=0.01\) (dimensionless) and \(A=5.0\mathrm{m}^2\).
Single pendulum with air resistance simulation code.
using DifferentialEquations, Plots, LaTeXStrings
ENV["GKSwstype"] = "100"
rho, Cd, A, g, m, l = 2.0, 0.01, 5.0, 9.81, 1.0, 1.0
fps = 30
function pendulum!(du, u, p, t)
du[1] = u[2]
du[2] = -(g/l)*cos(u[1])-rho*Cd*A*l*abs(u[2])*u[2]/(2*m)
end
tspan = (0.0, 10.0)
u0 = [0.0, 0.0] # θ₀ = 0, θ̇₀ = 0
prob = ODEProblem(pendulum!, u0, tspan)
sol = solve(prob, saveat=1/fps)
plot(sol.t, sol[1, :], label=false)
xlabel!(L"t\;(\mathrm{seconds})")
ylabel!(L"\theta\;(\mathrm{radians})")
savefig("Dampened_pendulum_theta.svg")
# Animate with θ measured counterclockwise from the positive x-axis
x = l .* cos.(sol[1, :])
y = l .* sin.(sol[1, :])
anim = @animate for i in eachindex(sol.t)
plot(
[0, x[i]], [0, y[i]];
xlims=(-1.1l, 1.1l),
ylims=(-1.1l, 0.05l),
aspect_ratio=:equal,
label=false,
xlabel=L"x\ (\mathrm{metres})",
ylabel=L"y\ (\mathrm{metres})"
)
scatter!([x[i]], [y[i]]; markersize=8, label=false)
end
gif(anim, "Dampened_pendulum.gif"; fps=fps)
Figure shows the plot produced by Code Listing . As you can see over time the maximum and minimum angle the pendulum forms gets closer and closer towards \(-\dfrac{\pi}{2}\). Figure shows the animation produced by the above Julia code. Dampened pendulum angle plot. Dampened pendulum animation.
A system consisting of two bodies in gravitational motion around each other. In this example, we are modelling the motion of a moving mass around a mass centred at the origin. The relationship between these polar coordinates and our Cartesian coordinates are, for our moving mass:
\[\begin{aligned} x &= r\cos{\theta} \\ y &= r\sin{\theta}. \end{aligned}\]
Their time derivatives are, by the product and chain rules:
Let \(u=\dfrac{1}{r}\). Then \(r=\dfrac{1}{u}\) and \(\dot{r}=-\dfrac{\dot{u}}{u^2}\). We are going to focus on geometrically solving this problem, so we will convert our differential equation from being with respect to \(t\) to being with respect to \(\theta\). Hence:
This is the equation for a conic section (parabola, hyperbola or ellipse) with \(e\) as its eccentricity and \(\theta_0\) is the angle at which the moving mass is closest to the central mass. If \(0 \leq e < 1\), it is an ellipse (\(e=0\) makes it a perfect circle); if \(e=1\), it is a parabola; and if \(e>1\), it is a hyperbola.
So this establishes to us that Lagrangian mechanics predicts that an object in orbit around a larger, central mass, will move in a conic section orbit. For the Moon's orbit around the Earth, \(e\) is also almost \(0\). For all the planets in the Solar System, their \(e\) values are between \(0\) and \(1\), giving them elliptical orbits, too.
I thought a good example for you would be the gravitational three-body problem. As like the double pendulum problem, it exhibits chaos. Further, it is the premise of a popular scifi Netflix series 3 Body Problem, which is based on a novel called Remembrance of Earth's Past. As you can see in Figure , our axes are selected such that the mass \(M\) is centred at the origin. Consequently, the central mass does not move on our axes. So only the two other masses contribute to our system's kinetic energy:
\[\begin{aligned} T &= \dfrac{m_1}{2}(\dot{r}_1^2 + r_1^2 \dot{\theta}_1^2) + \dfrac{m_2}{2}(\dot{r}_2^2+r_2^2\dot{\theta}_2^2). \end{aligned}\]
I omitted the calculation of the velocity of the two moving bodies as they are identical to the velocity calculation for the two-body problem.
To calculate the potential energy, we will need to calculate \(r_{12}\), the distance between the masses \(m_1\) and \(m_2\). To calculate this, we will start with the \(x\) and \(y\) coordinates for the two moving masses:
Hence the difference in \(x\) is \(r_2\cos{\theta_2} - r_1\cos{\theta_1}\) and the difference in \(y\) is \(r_2\sin{\theta_2}-r_1\sin{\theta_1}\). Hence:
We deliberately ignored the negative possibility as \(r_{12}\) is defined such that it must be non-negative. Hence the gravitational potential energy of our system:
\[\begin{aligned} V &= -\dfrac{GMm_1}{r_1} - \dfrac{GMm_2}{r_2} - \dfrac{Gm_1m_2}{r_{12}}. \end{aligned}\]
The first of these terms is the potential energy for the gravitational attraction between the central mass and \(m_1\). The second is the potential energy for the gravitational attraction between the central mass and \(m_2\). The third is the potential energy for the gravitational attraction between \(m_1\) and \(m_2\).
Hence the Lagrangian is:
\[\begin{align} L &= T - V \tag{59} \\ &= \dfrac{m_1}{2}(\dot{r}_1^2 + r_1^2 \dot{\theta}_1^2) + \dfrac{m_2}{2}(\dot{r}_2^2+r_2^2\dot{\theta}_2^2) + \dfrac{GMm_1}{r_1} + \dfrac{GMm_2}{r_2} + \dfrac{Gm_1m_2}{r_{12}}. \tag{60} \end{align}\]
We will calculate \(\dfrac{\partial r_{12}}{\partial q_i}\) as this will come in handy when finding \(\dfrac{\partial L}{\partial q_i}\).
Equations (62), (64), (65) and (66) cannot be analytically solved, unlike the equations we obtained for the two-body problem. Consequently, we are forced to resort to numerical methods to solve this system.
Code Listing is Julia code to numerically solve the system for a made-up example of the three-body problem. We assume each of the orbits start out elliptical and \(a\) is their semi-major axis and \(e\) is their eccentricity. These parts of the initial conditions are:
We will start the simulation with each of the moving masses at their periapsis. Which is when they are at their closest point to the central mass. From this, we get the following initial conditions:
using DifferentialEquations
using Plots, Measures, Colors
using Printf, LaTeXStrings
ENV["GKSwstype"] = "100"
# ============================================================
# Three-body gravitational system
#
# Body M is fixed at the origin.
# Bodies m₁ and m₂ orbit M while also perturbing one another.
#
# Unlike a strongly hierarchical system, the masses here are
# comparable enough for the mutual interaction to produce
# strongly non-Keplerian and potentially chaotic motion.
#
# Units are normalised:
# G = 1
# mass = arbitrary mass unit
# distance = arbitrary distance unit
# time = corresponding dynamical time unit
# ============================================================
# ------------------------------------------------------------
# Parameters
# ------------------------------------------------------------
G = 1.0
M = 3.0
m₁ = 1.5
m₂ = 2.0
a₁ = 5.0
e₁ = 0.15
a₂ = 5.0
e₂ = 0.10
θ₁₀ = 0.0
θ₂₀ = π - 0.15
tspan = (0.0, 200.0)
abstol = 1e-11
reltol = 1e-11
fps = 60
marksize = 10
stepsize = 10/fps
legendfontsize = 24
guidefontsize = 24
tickfontsize = 20
titlefontsize = 30
# ------------------------------------------------------------
# Initial approximate Keplerian orbits
# ------------------------------------------------------------
# Periapsis distances
r₁₀ = a₁ * (1 - e₁)
r₂₀ = a₂ * (1 - e₂)
# ------------------------------------------------------------
# Initial Keplerian periapsis velocities
# ------------------------------------------------------------
v₁₀ = sqrt(G * M * (1 + e₁) / r₁₀)
v₂₀ = sqrt(G * M * (1 + e₂) / r₂₀)
# Radial velocity is zero at periapsis.
ṙ₁₀ = 0.0
ṙ₂₀ = 0.0
# Since v = r θ̇:
θ̇₁₀ = v₁₀ / r₁₀
θ̇₂₀ = v₂₀ / r₂₀
# ------------------------------------------------------------
# Initial state vector
#
# u = [
# r₁,
# r₂,
# θ₁,
# θ₂,
# ṙ₁,
# ṙ₂,
# θ̇₁,
# θ̇₂
# ]
# ------------------------------------------------------------
u₀ = [
r₁₀,
r₂₀,
θ₁₀,
θ₂₀,
ṙ₁₀,
ṙ₂₀,
θ̇₁₀,
θ̇₂₀
]
# ------------------------------------------------------------
# Equations of motion
# ------------------------------------------------------------
function three_body!(du, u, p, t)
r₁, r₂, θ₁, θ₂, ṙ₁, ṙ₂, θ̇₁, θ̇₂ = u
Δθ = θ₂ - θ₁
r₁₂ = sqrt(
r₁^2 +
r₂^2 -
2*r₁*r₂*cos(Δθ)
)
# --------------------------------------------------------
# Radial accelerations
# --------------------------------------------------------
r̈₁ =
r₁*θ̇₁^2 -
G*M/r₁^2 -
G*m₂*(r₁ - r₂*cos(Δθ))/r₁₂^3
r̈₂ =
r₂*θ̇₂^2 -
G*M/r₂^2 -
G*m₁*(r₂ - r₁*cos(Δθ))/r₁₂^3
# --------------------------------------------------------
# Angular accelerations
# --------------------------------------------------------
θ̈₁ =
-2*ṙ₁*θ̇₁/r₁ +
G*m₂*r₂*sin(Δθ)/(r₁*r₁₂^3)
θ̈₂ =
-2*ṙ₂*θ̇₂/r₂ -
G*m₁*r₁*sin(Δθ)/(r₂*r₁₂^3)
# --------------------------------------------------------
# First-order system
# --------------------------------------------------------
du[1] = ṙ₁
du[2] = ṙ₂
du[3] = θ̇₁
du[4] = θ̇₂
du[5] = r̈₁
du[6] = r̈₂
du[7] = θ̈₁
du[8] = θ̈₂
end
# ------------------------------------------------------------
# Integrate
#
# 100 time units gives the system ample time to undergo
# several orbital periods and develop strongly perturbed
# trajectories.
# ------------------------------------------------------------
prob = ODEProblem(
three_body!,
u₀,
tspan
)
solut = solve(
prob,
Vern8(),
saveat=stepsize,
abstol=abstol,
reltol=reltol
)
# ------------------------------------------------------------
# Convert polar coordinates to Cartesian coordinates
# ------------------------------------------------------------
x₁ = solut[1, :] .* cos.(solut[3, :])
y₁ = solut[1, :] .* sin.(solut[3, :])
x₂ = solut[2, :] .* cos.(solut[4, :])
y₂ = solut[2, :] .* sin.(solut[4, :])
# ------------------------------------------------------------
# Calculate body-body separation
# ------------------------------------------------------------
separation = sqrt.(
(x₂ .- x₁).^2 +
(y₂ .- y₁).^2
)
# ------------------------------------------------------------
# Plot limits
# ------------------------------------------------------------
x_all = vcat(0.0, x₁, x₂)
y_all = vcat(0.0, y₁, y₂)
xmin = minimum(x_all)
xmax = maximum(x_all)
ymin = minimum(y_all)
ymax = maximum(y_all)
span = max(
xmax - xmin,
ymax - ymin
)
margin = 0.08 * span
xc = (xmin + xmax) / 2
yc = (ymin + ymax) / 2
xmin = xc - span/2 - margin
xmax = xc + span/2 + margin
ymin = yc - span/2 - margin
ymax = yc + span/2 + margin
# ------------------------------------------------------------
# Animation
# ------------------------------------------------------------
m1col = RGB24(0, 0, 155/255)
m1outcol = RGB24(190/255, 190/255, 255/255)
m2col = RGB24(0, 155/255, 155/255)
m2outcol = RGB24(190/255, 255/255, 255/255)
Mcol = RGB24(65/255, 130/255, 65/255)
anim = @animate for i in eachindex(solut.t)
p = plot(
x₁[1:i],
y₁[1:i],
linewidth=1,
color=m1col,
label=false,
xlims=(xmin, xmax),
ylims=(ymin, ymax),
aspect_ratio=:equal,
xlabel=L"x",
ylabel=L"y",
title="Three-body system — t = $(@sprintf("%.2f", solut.t[i]))",
guidefontsize=guidefontsize,
tickfontsize=tickfontsize,
titlefontsize=titlefontsize,
legend=:topleft,
legendfontsize=legendfontsize,
left_margin=2Plots.mm,
right_margin=2Plots.mm,
top_margin=2Plots.mm,
bottom_margin=2Plots.mm,
size=(1600, 1600)
)
plot!(
p,
x₂[1:i],
y₂[1:i],
linewidth=1,
color=m2col,
label=false
)
# Central body
scatter!(
p,
[0.0],
[0.0],
markershape=:circle,
markersize=marksize,
color=Mcol,
markerstrokecolor=Mcol,
label="M"
)
# Body 1
scatter!(
p,
[x₁[i]],
[y₁[i]],
markershape=:circle,
markersize=round(marksize/2),
color=m1col,
markerstrokecolor=m1outcol,
label="m₁"
)
# Body 2
scatter!(
p,
[x₂[i]],
[y₂[i]],
markershape=:circle,
markersize=round(marksize/2),
color=m2col,
markerstrokecolor=m2outcol,
label="m₂"
)
end
# ------------------------------------------------------------
# Save GIF
#
# saveat = 1/fps
# fps = fps
#
# Therefore one simulated second corresponds to one second
# of animation playback.
# ------------------------------------------------------------
gif(
anim,
"three_body_system.gif",
fps=fps
)
As you can see, the orbits majorly and seemingly unpredictably change over time. This is pretty typical in the three-body problem: either the orbits are fairly stable and unchanging, or they are unstable and prone to objects being ejected from the system or colliding with one another.
Three-body system simulation for the above parameters.
In this section, we will try to generalize our Lagrangian and system of equations from the previous section so that they are applicable to a gravitational system with an arbitrary number of bodies. Let \(M\) denote the static central mass, \(m_i\) the \(i\)th moving mass, \(r_i\) the distance from the central mass to the \(i\)th moving mass, \(\theta_i\) is the angle between the line formed by \(r_i\) and the positive \(x\)-axis, measured counter-clockwise. Which is essentially how we defined things in Figure .
So kinetic energy for this system should be pretty straight forward, namely it should simply be the sum of the kinetic energy of each individual body, in other words it should be:
\[\begin{aligned} T &= \sum_{i=1}^{n-1} \dfrac{m_i(\dot{r}_i^2+r_i^2\dot{\theta}_i^2)}{2}. \end{aligned}\]
Where \(m_i\) is the \(i\)th moving body. As for potential energy, well there will be terms for the interaction between each of the \(n\) bodies. For interactions between the central mass and the moving bodies, these will simply be of the form \(-\dfrac{GMm_i}{r_i}\). As for the interactions between the moving bodies, their potential energy terms will be of the form \(-\dfrac{Gm_i m_j}{r_{ij}}\) where \(r_{ij}\) is the distance between masses \(i\) and \(j\). Hence:
As we can see, \(r_{ij} = r_{ji}\) due to cosine being an even function. Hence the potential energy is:
\[\begin{aligned} V &= -\sum_{i=1}^{n-1} \left(\dfrac{GMm_i}{r_i} + \sum_{j>i}^{n-1} \dfrac{Gm_i m_j}{r_{ij}}\right). \end{aligned}\]
Why the \(j>i\) on the second sum? Well, to ensure we do not count the same terms but with a different order of their indices (e.g. \(\dfrac{Gm_1 m_2}{r_{12}}\) and \(\dfrac{Gm_2 m_1}{r_{21}}\) are equivalent despite the different order of indices) twice. Hence:
The \(\delta_{ik}\) imposes that \(i=k\). Since \(j>i\) we get \(j=k+1, k+2, k+3, ..., n-1\). So we are left only with the \(j\) sum for terms multiplied by \(\delta_{ik}\). As for \(\delta_{jk}\), it imposes that \(j=k\) which then requires, given \(j>i\), that \(i=1,2,3,...,k-1\).
An important verification of our working is that if \(n=3\), we should get the same equations as we obtained in gravitational three-body problem. If \(n=3\), we get for \(\ddot{r}_1\):
Code Listing produces the animation in Figure . It solves Equations (71) and (72) for \(n=4\) with the following initial conditions. We assume each of the orbits start out elliptical and \(a\) is their semi-major axis and \(e\) is their eccentricity. These parts of the initial conditions are:
We will start each of the moving masses at their periapsis. From this, we get the initial conditions Equations (67), (68), (69), and (70). As for \(G\) and the masses, they are the same as for the three-body problem simulation, except:
\[\begin{aligned} m_3 &= 0.01. \end{aligned}\]
This relatively small \(m_3\) was chosen to represent potentially a planet in this system whereas the other masses are potentially stars. Why did I choose this? Because this system reminds me of the Netflix series 3 Body Problem. As for the initial angles they are the same as for the three-body problem simulation, except:
The lack of most units is deliberate, as we are not analysing a real system. The numbers were chosen just to make the system's behaviour interesting. N-body problem simulation code.
using DifferentialEquations
using Plots, Measures, Colors
using Printf, LaTeXStrings
ENV["GKSwstype"] = "100"
# ============================================================
# N-body gravitational system with a fixed central mass
#
# M is fixed at the origin.
# N orbiting bodies interact gravitationally with M and with
# one another.
#
# State vector:
# u = [r₁,...,rₙ, θ₁,...,θₙ, ṙ₁,...,ṙₙ, θ̇₁,...,θ̇ₙ]
#
# All quantities use normalized units.
# ============================================================
# ------------------------------------------------------------
# Parameters
# ------------------------------------------------------------
# Add or remove entries to change the number of orbiting bodies.
# All parameter vectors must have the same length.
G = 1.0
M = 3.0
masses = [1.5, 2.0, 0.01]
N = length(masses)
# Initial conditions
## Semi-major axes
a = [5.0, 5.0, 15.0]
## Eccentricities
e = [0.20, 0.05, 0.01]
## Initial angular positions
θ₀ = [
0.0
π - 0.15
π/3 + 0.06
]
# Frames per second of animation
fps = 60
# Solution params
tspan = (0.0, 60.0)
abstol = 1e-11
reltol = 1e-11
stepsize = 8/fps
# Animation params
marksize = 10
legendfontsize = 24
guidefontsize = 24
tickfontsize = 20
titlefontsize = 30
# ------------------------------------------------------------
# Validate parameters
# ------------------------------------------------------------
@assert N >= 1 "At least one orbiting body is required."
@assert length(a) == N "The semimajor axis vector must have N entries."
@assert length(e) == N "The eccentricity vector must have N entries."
@assert all(>(0), masses) "All orbiting masses must be positive."
@assert all(>(0), a) "All semimajor axes must be positive."
@assert all(x -> 0 <= x < 1, e) "Eccentricities must satisfy 0 ≤ e < 1."
# ------------------------------------------------------------
# Initial approximate Keplerian orbits
# ------------------------------------------------------------
# Periapsis distances
r₀ = a .* (1 .- e)
# Initial Keplerian periapsis velocities
v₀ = sqrt.(G .* M .* (1 .+ e) ./ r₀)
# Radial velocities vanish at periapsis.
ṙ₀ = zeros(N)
# Since v = r θ̇:
θ̇₀ = v₀ ./ r₀
# ------------------------------------------------------------
# Initial state vector
# ------------------------------------------------------------
u₀ = vcat(
r₀,
θ₀,
ṙ₀,
θ̇₀
)
# ------------------------------------------------------------
# Equations of motion
# ------------------------------------------------------------
function n_body!(du, u, p, t)
G, M, masses, N = p
# Obtain views of the state vector.
r = @view u[1:N]
θ = @view u[N+1:2N]
ṙ = @view u[2N+1:3N]
θ̇ = @view u[3N+1:4N]
# Obtain views of the derivative vector.
dr = @view du[1:N]
dθ = @view du[N+1:2N]
dṙ = @view du[2N+1:3N]
dθ̇ = @view du[3N+1:4N]
# First-order kinematic equations.
dr .= ṙ
dθ .= θ̇
# --------------------------------------------------------
# Gravitational accelerations
# --------------------------------------------------------
for k in 1:N
# Angular differences relative to body k.
Δθ = θ .- θ[k]
# Distances between body k and every other body.
rᵢₖ = sqrt.(
r[k]^2 .+
r.^2 .-
2 .* r[k] .* r .* cos.(Δθ)
)
# Exclude self-interaction.
rᵢₖ[k] = Inf
# ----------------------------------------------------
# Radial acceleration
# ----------------------------------------------------
radial_interaction = sum(
masses .* (
r[k] .- r .* cos.(Δθ)
) ./ rᵢₖ.^3
)
r̈ₖ =
r[k]*θ̇[k]^2 -
G*M/r[k]^2 -
G*radial_interaction
# ----------------------------------------------------
# Angular acceleration
# ----------------------------------------------------
angular_interaction = sum(
masses .* r .* sin.(Δθ) ./ rᵢₖ.^3
)
θ̈ₖ =
-2*ṙ[k]*θ̇[k]/r[k] +
G*angular_interaction/r[k]
dṙ[k] = r̈ₖ
dθ̇[k] = θ̈ₖ
end
end
# ------------------------------------------------------------
# Integrate
# ------------------------------------------------------------
p = (G, M, masses, N)
prob = ODEProblem(
n_body!,
u₀,
tspan,
p
)
solut = solve(
prob,
Vern8(),
saveat=stepsize,
abstol=abstol,
reltol=reltol
)
# ------------------------------------------------------------
# Convert polar coordinates to Cartesian coordinates
# ------------------------------------------------------------
x = [
solut[k, :] .* cos.(solut[N+k, :])
for k in 1:N
]
y = [
solut[k, :] .* sin.(solut[N+k, :])
for k in 1:N
]
# ------------------------------------------------------------
# Calculate pairwise separations
# ------------------------------------------------------------
separations = Dict{Tuple{Int,Int},Vector{Float64}}()
for k in 1:N-1
for i in k+1:N
separations[(k,i)] = sqrt.(
(x[k] .- x[i]).^2 .+
(y[k] .- y[i]).^2
)
end
end
# ------------------------------------------------------------
# Plot limits
# ------------------------------------------------------------
x_all = vcat([0.0], x...)
y_all = vcat([0.0], y...)
xmin = minimum(x_all)
xmax = maximum(x_all)
ymin = minimum(y_all)
ymax = maximum(y_all)
span = max(xmax - xmin, ymax - ymin)
margin = 0.08 * span
xc = (xmin + xmax)/2
yc = (ymin + ymax)/2
xmin = xc - span/2 - margin
xmax = xc + span/2 + margin
ymin = yc - span/2 - margin
ymax = yc + span/2 + margin
# ------------------------------------------------------------
# Colours
# ------------------------------------------------------------
palette = [
RGB(0.0, 0.0, 0.65), # Dark blue
RGB(0.0, 0.55, 0.55), # Dark teal
RGB(0.65, 0.0, 0.0), # Dark red
RGB(0.45, 0.0, 0.65), # Purple
RGB(0.0, 0.45, 0.15), # Dark green
RGB(0.65, 0.25, 0.0), # Dark orange
RGB(0.25, 0.25, 0.25), # Dark grey
RGB(0.0, 0.4, 0.65) # Steel blue
]
bodycolors = [palette[mod1(k, length(palette))] for k in 1:N]
centralcolor = RGB24(65/255, 130/255, 65/255)
# ------------------------------------------------------------
# Animation
# ------------------------------------------------------------
anim = @animate for frame in eachindex(solut.t)
p = plot(
xlims=(xmin, xmax),
ylims=(ymin, ymax),
aspect_ratio=:equal,
xlabel=L"x",
ylabel=L"y",
title="$(N+1)-body system — t = $(@sprintf("%.2f", solut.t[frame]))",
guidefontsize=guidefontsize,
tickfontsize=tickfontsize,
titlefontsize=titlefontsize,
legend=:topleft,
legendfontsize=legendfontsize,
left_margin=2Plots.mm,
right_margin=2Plots.mm,
top_margin=2Plots.mm,
bottom_margin=2Plots.mm,
size=(1600, 1600)
)
# Plot trajectories and current positions.
for k in 1:N
plot!(
p,
x[k][1:frame],
y[k][1:frame],
linewidth=1,
color=bodycolors[k],
label=false
)
scatter!(
p,
[x[k][frame]],
[y[k][frame]],
markershape=:circle,
markersize=round(marksize/2),
color=bodycolors[k],
markerstrokecolor=bodycolors[k],
label=latexstring("m_{$k}")
)
end
# Central body.
scatter!(
p,
[0.0],
[0.0],
markershape=:circle,
markersize=marksize,
color=centralcolor,
markerstrokecolor=centralcolor,
label="M"
)
end
# ------------------------------------------------------------
# Save GIF
#
# saveat = 1/fps
# fps = fps
#
# One simulated second corresponds to one second of playback.
# ------------------------------------------------------------
gif(
anim,
"n_body_system.gif",
fps=fps
)
As you can see, the orbits majorly and seemingly unpredictably change over time. This is pretty typical in the \(n\)-body problem: either the orbits are fairly stable and unchanging (like the orbits of the planets in the Solar System), or they are unstable and prone to objects being ejected from the system or colliding with one another.
Four-body system simulation for the above parameters.
Double pendulum diagram. I thought it would be instructive for me to show you how to derive the equations of motion for the simplest sort of double pendulum. One where there is no air resistance, no friction, and the rods are both massless. Then the coordinates of the first bob are:
Ideally, we want one equation for \(\ddot{\theta}_1\) (and \(\ddot{\theta}_1\) alone) and another \(\ddot{\theta}_2\). So let us put our system into matrix form:
In Hamiltonian mechanics, we can usually define the Hamiltonian as:
\[\begin{align} H &= T + V. \tag{74} \end{align}\]
Which is the total energy of our system. More generally we define the Hamiltonian as:
\[\begin{align} H &\stackrel{\text{def}}{=} \sum_{i=1}^n p_i \dot{q}_i - L. \tag{75} \end{align}\]
Equation (75) is called the Legendre transformation of the Lagrangian. So when are Equations (74) and (75) not equivalent? The answer is when our potential energy depends, at least in part, on the generalized velocities. Another difference from Lagrangian mechanics is that we define \(H\) in terms of \(p_i\) and \(q_i\) instead of \(q_i\) and \(\dot{q}_i\).
So what is the Legendre transformation? It takes a function, say \(f(x)\), and it uses its tangent lines and their \(y\) intercepts to create a new function, \(g(p)\) that incorporates all the information that \(f(x)\) contained. Here is a great video that explains the Legendre transformation and its derivation.
The equations of motion with no non-conservative forces are:
To go from Equations (78) to (79), we used the product rule of differentiation, in case you were wondering. Next we use the definition of canonical momentum:
Next we can use Equations (43) to simplify our \(\dfrac{\partial L}{\partial q_i}\) term. As remember this, according to Equations (43) is equal to \(\dfrac{d}{dt}\dfrac{\partial L}{\partial \dot{q}_i}\) which can also be written as \(\dot{p}_i\):
As this is just the change in \(H\) caused directly by the change in \(q_i\) plus the change in \(H\) that is directly caused by the change in \(p_i\). Equating like terms in the right-hand sides of Equations (80) and (81) yields:
Which are Equations (76) and (77). I should mention this is not the only way to derive Hamilton's equations; it is also possible to derive them directly from the stationary action principle, for instance.
To account for non-conservative forces, we merely add the corresponding generalized force terms to the right-hand side of Equation (76). In other words:
Hamilton's equations creates a new kind of space that we can visualize our solution on that has dimensions \(q_i\) and \(p_i\). This type of space is known as phase space.
There is a class of methods for numerically integrating Hamilton's equations specifically; they are called symplectic integration schemes. Unlike the numerical integration schemes we have previously covered, symplectic integration schemes are designed to specifically keep the Hamiltonian unchanged over time. Other numerical integration techniques when applied to Hamilton's equations with small step sizes or low error tolerances will largely leave the Hamiltonian unchanged in the short-term, simply because the differential equation itself keeps the Hamiltonian unchanged. Over the long-term small errors from approximating the solution with these schemes can accumulate to markedly change the Hamiltonian, however.
\[\begin{align} H &= T + V \tag{83} \\ &= \dfrac{ml^2 \dot{\theta}^2}{2} + mgl\sin{\theta}. \tag{84} \end{align}\]
We can use Equation (74) to determine our Hamiltonian here because our potential energy, \(V\), is independent of the generalized velocities. Problem is, however, that this is written in terms of \(q_i\) and \(\dot{q}_i\) not \(q_i\) and \(p_i\). First we need to determine what our canonical momentum is. Equations (48) yields:
As we can see, Hamiltonian mechanics yields a series of first-order ODEs instead of second-order ODEs. Which is important because Lagrangian mechanics and Newtonian mechanics both yield second-order ODE systems. That being said, if you rewrite Equation (89) to make \(p_{\theta}\) its subject and substitute it into Equation (88) and rearrange it to make \(\ddot{\theta}\) the subject, you will obtain Equation (53).
Code Listing is Julia code for solving Equations (88) and (89) with \(-\dfrac{\pi}{2} + 0.1 \leq \theta_0 \leq \dfrac{\pi}{2}-0.1\) and \(-0.1 \leq p_{\theta_0} \leq 0.1\) and producing a phase plot for the solutions. For all the solutions the gravitational acceleration (\(g\)) was assumed to be 9.81\(\mathrm{m}\cdot \mathrm{s}^{-2}\), \(l\) was assumed to be \(1\)m and \(m\) was assumed to be \(1\)kg. Phase plot for the simple pendulum.
using DifferentialEquations, Plots, LaTeXStrings
ENV["GKSwstype"] = "100"
g, m, l = 9.81, 1.0, 1.0
function pendulum!(du, u, p, t)
du[1] = u[2]/(m*l^2)
du[2] = -m*g*l*cos(u[1])
end
tspan = (0.0, 10.0)
ics = [(θ₀, pθ₀) for θ₀ in range(-π/2+0.1, π/2-0.1, length=9), pθ₀ in range(-0.1, 0.1, length=3)]
plot()
for u₀ in ics
local sol = solve(ODEProblem(pendulum!, collect(u₀), tspan))
plot!(sol, idxs=(1, 2), label=false)
end
xlabel!(L"\theta (\mathrm{rad})")
ylabel!(L"p_{\theta}(\mathrm{kg}\cdot\mathrm{m}^2\cdot\mathrm{rad}\cdot\mathrm{s}^{-1})")
savefig("Phase_plot.svg")
Figure shows the phase plot generated by the above Julia code. Each differently-coloured line represents a different value of \(\theta_0\) and \(p_{\theta_0}\). These elliptical lines are called "orbits" in the phase plot. \(H\) is constant for a given orbit and the different orbits correspond to different \(H\) values. Phase plot for the simple pendulum.
In Figure , we see the orbits for a given set of initial conditions are closed systems. But this is for a conservative system; for non-conservative systems, where the Hamiltonian is not constant, the orbits are not closed systems and instead spiral towards the origin. Say we add Equation (56) to the right-hand side of Equation (88). This yields:
using DifferentialEquations, Plots, LaTeXStrings
ENV["GKSwstype"] = "100"
g, m, l = 9.81, 1.0, 1.0
rho, Cd, A = 2.0, 0.05, 5.0
function pendulum!(du, u, p, t)
du[1] = u[2]/(m*l^2)
du[2] = -m*g*l*cos(u[1]) - rho*Cd*A*abs(u[2])*u[2]/(2*m^2*l)
end
tspan = (0.0, 100.0)
theta0 = pi/2-0.01
ptheta0 = 0
plot()
solut = solve(ODEProblem(pendulum!, [theta0, ptheta0], tspan))
plot!(solut, idxs=(1, 2), label=false)
xlabel!(L"\theta (\mathrm{rad})")
ylabel!(L"p_{\theta}(\mathrm{kg}\cdot\mathrm{m}^2\cdot\mathrm{rad}\cdot\mathrm{s}^{-1})")
savefig("Phase_plot_dampened.svg")
Figure shows the phase plot generated by the above Julia code. In this phase plot, \(\theta_0=\dfrac{pi}{2}-0.1\) and \(p_{\theta_0}=0\). As you can see, the orbit is unstable and gradually gets closer to the origin. This is due to energy loss from the system. I am only showing one solution in the phase plot because, as the system is non-conservative, the orbits all spiral towards the origin and this would cause a lot of confusing overlap if I included multiple solutions. Phase plot of the dampened pendulum.
Let us analyse what happens when a projectile is fired into the air. Let \(x\) represent the horizontal direction and \(y\) represent the vertical direction. Our potential energy here would be \(mgy\), hence it is independent of the generalized velocities and we can use the \(H=T+V\) definition of the Hamiltonian.
\[\begin{aligned} H &= \dfrac{m}{2}(\dot{x}^2+\dot{y}^2) + mgy. \end{aligned}\]
Poisson brackets provide us an elegant and powerful way to rewrite Hamilton's equations. If we have \(n\) degrees of freedom and two functions \(f\) and \(g\) that depend on \(p_i\) and \(q_i\) (Cline, 2026) :
The quality of two functions, say \(f\) and \(g\), having a Poisson bracket that equals zero is phrased as \(f\) and \(g\) commuting under the Poisson bracket.
If a function \(f(q_i, p_i)\) is not explicitly dependent on \(t\) and only depends on \(t\) indirectly through \(q_i\) and \(p_i\), then, via the chain rule:
Hence commuting with the Hamiltonian under the Poisson bracket is a sufficient condition for a quantity that does not explicitly depend on time to have a zero time derivative. A zero time derivative means the quantity is static over time which means it is conserved.
This quality makes it unsurprising that Hamilton's equations can be rewritten as:
Noether's theorem essentially states that for every continuous symmetry in the Lagrangian, there is a corresponding conservation law. For instance, time translation symmetry of the Lagrangian yields the conservation of energy. To show this, we will assume our Lagrangian does not explicitly depend on \(t\). That is, \(t\) itself does not appear directly in our Lagrangian. The only time dependence \(L\) has on \(t\) is through the dependence of \(q_i\) and \(\dot{q}_i\) on time. If the Lagrangian did explicitly depend on time, we would expect it not to have time translation symmetry. Say we increase time according to the transformation: \(t\rightarrow t+dt\) where \(dt\) is an infinitesimal change in \(t\).
If you are wondering what about if we have non-conservative forces? Would that not mean Equations (44) would not hold as there would be a missing generalized force term? Yes and in that event the Lagrangian would indeed change in time and conservation of energy would not hold, as our system would be losing energy to those non-conservative forces. Substituting Equations (48) into Equation (112) yields:
We could now use Equation (75) to simplify Equation (115), but I would like to use this as an opportunity to show you how Equations (74) and (75) are usually equivalent. Interestingly, \(\displaystyle\sum_{i=1}^n p_i \dot{q}_i=2T\), that is it is twice the kinetic energy of our system. We can establish this identity using Euler's theorem for homogeneous functions.
Say we have a homogeneous function \(f\) of degree \(m\) of the form:
where \(a_{i,j,k,...,}\) are coefficients that do not depend on our variables. In other words, \(f\) is a polynomial function of \(x_i\) (\(i\in\{1, 2, 3, ..., n\}\)) with a maximum total power of \(m\). Then Euler's theorem states that (Tatum, 2026) :
So we see that Equations (74) and (75) are equivalent if and only if potential energy is independent of generalized velocity. We also obtain that the Hamiltonian — which is the total energy of the system if potential energy is independent of generalized velocity — does not change when the Lagrangian is time symmetric, hence it is conserved.
I should also mention that the Hamiltonian formulation of Noether's theorem uses Equation (105). As if a quantity that does not explictly depend on time commutes with the Hamiltonian under the Poisson bracket, this means it does not change over time and hence is conserved.
There is a final formulation of classical mechanics that I should probably cover. It is based around the so called Hamilton-Jacobi equation which is of the form:
Where \(S\) is the action, which is also called Hamilton's principal function. In this approach, we essentially write our Hamiltonian in terms of \(p_i\) and \(q_i\) and then replace the \(p_i\) with \(\dfrac{\partial S}{\partial q_i}\). If our Hamiltonian does not explicitly depend on time, which is usually the case, we then use a separation of variables of the form:
Where \(W\) is called Hamilton's characteristic function or the abbreviated action and \(E\) is the constant energy.
This approach to mechanics actually lead directly to the Schrödinger equation. Schrödinger actually derived his equation from the Hamilton-Jacobi equation. Why? Well, out of the formulations of classical mechanics, the Hamilton-Jacobi equation allows us to describe mechanical systems in a way that is analogous to light waves. The wave-particle duality — the idea that every quantum particle, including electrons and photons, exhibit both wave and particle properties — is a fundamental part of quantum mechanics and hence the Hamilton-Jacobi equation provides a particularly natural starting point for the development of the central equation of quantum mechanics. For an explanation for how we can describe a mechanical system in a way analogous to light waves, I suggest you check out this excellent video by Abide by Reason.
To see the Hamilton-Jacobi equation in action, let us apply it to the simple pendulum. Replacing \(p_{\theta}\) with \(\dfrac{\partial S}{\partial \theta}\):
\[\begin{aligned} H &= \dfrac{\left(\dfrac{\partial S}{\partial \theta}\right)^2}{2ml^2}+mgl\sin{\theta}. \end{aligned}\]
The integrand — given it is integrated with respect to \(\theta\) to obtain \(t\) (plus some constant) — must be \(\dfrac{dt}{d\theta}\) which is one over \(\dfrac{d\theta}{dt}\) or \(\dot{\theta}\). Therefore:
Classical mechanics provides the foundation that other fields of physics build on.
For instance, special relativity provides corrections (often called relativistic corrections) to classical mechanics to account for effects that become pronounced at speeds comparable to \(c\), the speed of light in a vacuum. General relativity accounts for these effects, too, but also accounts for effects most noticeable in strong gravitational fields.
Quantum mechanics instead focuses on what happens on small scales, namely the scale of atoms and subatomic particles. Like classical mechanics, quantum mechanics does not account for effects that become pronounced at speeds comparable to \(c\).
Quantum field theory focuses on quantum fields, such as those pertaining to electromagnetism, the strong nuclear force and the weak nuclear force. It also has the distinction of being relativistic — that is, it accounts for effects that become pronounced at speeds comparable to \(c\).
As previously mentioned, in special relativity we can make relativistic corrections to kinetic energy in our Lagrangian and Hamiltonians. Namely, we can define it as:
Using the Maclaurin series, we are going to show that \(T(v)\) is well approximated by \(T=\dfrac{mv^2}{2}\) when \(v << c\). To make things simpler for ourselves, we will consider the Maclaurin series of the function:
(This is as opposed to directly calculating the Maclaurin series of our \(T(v)\). If we directly applied the Maclaurin series formula to \(T(v)\) the derivatives we would need to calculate would get a bit unruly.) In this case:
Where \(f^{(3)}(x)\) denotes the 3rd derivative of \(f\) with respect to \(x\). Note how for the first derivative the coefficient is just \(\dfrac{1}{2}\), for the second derivative it is \(\dfrac{3}{4}\) and for the third it is \(\dfrac{15}{8}\). Seems to me that the denominator is just \(2^n\) where \(n\) is the order of the derivative and the numerator of the coefficient is \((2n-1) \times (2n-3) \times (2n-5)\times ... \times 1\). Hence:
So what happens when \(v\) is much smaller than \(c\)? Well, we would expect every term with a non-zero power of \(c\) in the denominator to be negligible in its contribution to \(T\) and this leaves only the first term. Hence we obtain that for \(v << c\):
In general relativity, we can use the Einstein-Hilbert action to derive the Einstein field equations (EFEs). The EFEs are a series of partial differential equations that can be used to calculate the components of the metric tensor, \(g_{\mu\nu}\). The metric tensor is a type of matrix with sixteen total components that allow us to define proper time in curved spacetime. It has sixteen components because \(\mu\) and \(\nu\) can take on four different values each, corresponding to the four dimensions of spacetime (e.g. in Cartesian coordinates they are \(t\), \(x\), \(y\) and \(z\)), so that gives us \(4\times 4=16\) combinations of possible \(\mu\) and \(\nu\) values. Proper time is analogous to distance in spacetime and is the time that passes locally for an observer.
I should mention, in case you are unfamiliar, that in relativity, the passage of time itself is relative. Objects travelling close to the speed of light or in powerful gravitational fields have time pass substantially slower for them than those at lower velocities and in weaker gravitational fields.
The Einstein-Hilbert action is:
\[\begin{align} S &= \dfrac{c^4}{16\pi G} \int_{\mathbb{R}^4} R \sqrt{\left|\det{g_{\mu\nu}}\right|} d^4 x. \tag{130} \end{align}\]
One major difference you may notice between the classical action and the Einstein-Hilbert action is that the classical action is integrated over time whereas the Einstein-Hilbert action is integrated over spacetime (that is what the \(d^4x\) and \(\mathbb{R}^4\) are about). \(R\) is the Ricci scalar which is calculated based on \(g_{\mu\nu}\) and \(\det{g_{\mu\nu}}\) is the determinant of the metric tensor matrix.
Another application of action in general relativity is that it can be used to calculate the path an object will take in curved spacetime. As the path the object follows will be the path that maximizes its proper time. The action for this calculation is:
Why the \(-mc\) coefficient? Well, the negative sign is to ensure that minimizing \(S\) corresponds to maximizing the proper time. As for the \(mc\), it is to get our units right. See the integral itself is in units of metres. \(m\) is in units of kilograms and \(c\) is in units of metres per second. Consequently our units overall are \(\mathrm{kg} \cdot \mathrm{m}^2 \cdot \mathrm{s}^{-1}\). Action is in units of \(\mathrm{J}\cdot \mathrm{s}\), where \(\mathrm{J}\) denotes Joules, the SI standard unit of energy. Joules are, in turn, defined as \(\mathrm{kg}\cdot \mathrm{m}^2 \cdot \mathrm{s}^{-2}\). So \(\mathrm{J}\cdot \mathrm{s}\) is \(\mathrm{kg}\cdot \mathrm{m}^2 \cdot \mathrm{s}^{-1}\), which matches the units of our \(S\). I should also explain that in this integral, \(\lambda\) is an arbitrary parameter. Often we choose it to be proper time. Setting \(\delta S=0\) yields the geodesic equations which are a series of ordinary differential equations that maximize proper time.
We have seen in this article that there are multiple different formulations of classical mechanics. Similarly, there are multiple different formulations of quantum mechanics.
One formulation of quantum mechanics is the path-integral formulation developed by Richard Feynmann. In it, we expect our particle or wave to explore all possible paths and we integrate (or sum) over all those paths in order to compute the probability amplitude of our particle. The exploration of all possible paths is a consequence of the randomness of quantum mechanics. Specifically, we compute the integral:
Where \(K\) is the propagator, which specifies the probability amplitude for travelling from \(\mathbf{x}_0\) at time \(t_0\) to \(\mathbf{x}_f\) at time \(t_f\). \(S\) is the action of the particle, \(\hbar\) is the reduced Planck's constant, \(i\) is the imaginary number and \(\mathcal{D}\mathbf{x}\) refers to the fact we are integrating over all possible paths. The probability amplitude is a quantity that, if you take the absolute value of, and square this quantity you get the probability of the particle travelling from \(\mathbf{x}_0\) at time \(t_0\) to \(\mathbf{x}_f\) at time \(t_f\).
One major strength of the path-integral formulation of quantum mechanics is that it provides an explanation for how quantum mechanics gives rise to classical mechanics on larger scales.
So, with the background information covered in Prerequisite mathematics in mind, we now know that \(e^{\frac{iS}{\hbar}}\) is like a 2D unit vector as it points in particular direction in the \(xy\) plane and has unit length. Specifically, it points in the direction \(\dfrac{S}{\hbar}\) radians counterclockwise from the positive \(x\) axis. Each integer multiple of \(2\pi\), which corresponds to a complete revolution around the Cartesian plane, that is present in \(\dfrac{S}{\hbar}\) makes no difference to its overall direction. What matters is what is left after subtracting these integer multiples of \(2\pi\).
Interestingly, when we integrate over all possible paths on classical mechanics scales we find that the \(e^{\frac{iS}{\hbar}}\), for most paths, cancel each other out. To see why, we must first start with the fact that \(\hbar\) is a very tiny number — it is approximately \(1.055\times 10^{-34}\mathrm{J}\cdot \mathrm{s}\). Consequently, \(\dfrac{S}{\hbar}\) is a massive number when we are analysing classical mechanical systems. As typically in these scenarios \(S\) is \(\gt0.01\mathrm{J}\cdot \mathrm{s}\). As a result, even a relatively small difference in \(S\) can lead to a majorly different direction for \(e^{\frac{iS}{\hbar}}\).
This leads to the actions of nearby paths often being in opposite directions and cancelling each other when we calculate the path integral. The one exception is the path corresponding to the stationary action. Remember the equation \(\delta S=0\) that we solve to find the path of our classical mechanical system? It says that a tiny change to the stationary action path should make no change (to first order) to the action and consequently, when we integrate \(e^{\frac{iS}{\hbar}}\) for that path and its neighbours, the stationary action path term is the only one that survives. Consequently, in the classical limit our object only explores the path that extremizes the action, and as we have seen an extremized action leads to the equations of motion in classical mechanics.
Another connection between what we have covered and quantum mechanics is in the operator formalism of quantum mechanics. In it, we represent the state of our physical system using a function called the wavefunction which is denoted as \(\psi\), which can also thought of as a vector, as it is a complex number. We can calculate the wavefunction using Schrödinger's equation:
\(V(\mathbf{x})\) is the potential energy and \(\Delta\) is the Laplacian which is essentially just \(\dfrac{\partial^2}{\partial x^2} + \dfrac{\partial^2}{\partial y^2}+\dfrac{\partial^2}{\partial z^2}\). The right-hand side of Equation (133) can also be represented by \(\hat{H}\psi\) where \(\hat{H}\) is the Hamiltonian operator and calculates, from the wavefunction, the total energy of our system. Another important link to classical mechanics that I have already alluded to is that Schrödinger's equation was derived using the Hamilton-Jacobi equation. Specifically, Schrödinger used the Hamilton-Jacobi equation to derive an action that he then extremized and out from that popped his equation.
Lagrangians, Hamiltonians and actions also appear in quantum field theory, including The Standard Model of particle physics. In fact, if you want to see a dauntingly long and complex Lagrangian, Google The Standard Model Lagrangian.