Numerical Physics with Python: A Beginner’s Guide to Simulating Motion and Oscillations
computational-physicsPythonsimulationsnumerical-methodslab-resources

Numerical Physics with Python: A Beginner’s Guide to Simulating Motion and Oscillations

PPhysics Plus Editorial Team
2026-11-15
8 min read

Learn to build and test Python simulations for free fall, projectile motion, and harmonic oscillation using finite differences.

Numerical physics turns equations of motion into data you can inspect, plot, and test. This beginner-friendly workflow shows how to translate differential equations into finite-difference updates in Python, choose a sensible time step, compare numerical results with analytic solutions, and reuse the same checklist for projectile motion, free fall, and a simple harmonic oscillator.

Overview

A computer simulation does not solve most physics equations continuously. Instead, it evaluates an approximation at a sequence of discrete times. If the time step is dt, the simulation calculates the state at t, then estimates the state at t + dt.

For one-dimensional motion, the state commonly consists of position x and velocity v. Newton’s second law gives the acceleration:

a = F / m

A basic forward-Euler update is:

vnew = v + a dt
xnew = x + v dt

These formulas are finite-difference approximations. They become more accurate as dt becomes smaller, although a smaller time step also means more calculations. For many introductory physics problems, this trade-off is useful because the method is transparent: you can see how the acceleration changes velocity and how velocity changes position.

Use a consistent unit system before writing code. SI units are usually the simplest choice: metres, seconds, kilograms, and newtons. A quick dimensional check can catch errors that a program will otherwise calculate without complaint. The dimensional analysis guide is useful when checking formulas and conversions, while the physics constants and units reference can help when a model uses standard constants.

A reusable simulation has five parts: define parameters, create a time grid, update the state, store results, and compare or plot the output. The following Python examples use NumPy for arrays and Matplotlib for graphs.

import numpy as np
import matplotlib.pyplot as plt

# Example time grid
dt = 0.01
t_final = 5.0
t = np.arange(0, t_final + dt, dt)

x = np.zeros_like(t)
v = np.zeros_like(t)

# Set initial conditions
x[0] = 0.0
v[0] = 10.0

for i in range(len(t) - 1):
    a = 0.0                 # replace with the model's acceleration
    v[i + 1] = v[i] + a * dt
    x[i + 1] = x[i] + v[i] * dt

plt.plot(t, x)
plt.xlabel("Time (s)")
plt.ylabel("Position (m)")
plt.grid(True)
plt.show()

Keeping the loop explicit is helpful while learning. Once the model is understood, you can package it into functions or use more advanced numerical integrators.

Checklist by scenario

1. Free fall

For vertical motion near Earth’s surface, assume a constant downward acceleration g. Choose a sign convention first. In the example below, upward is positive, so the acceleration is a = -g. The analytic solution for an object released from height y0 with initial velocity v0 is:

y(t) = y0 + v0t - ½gt²

The simulation and analytic curve should approach one another as the time step is reduced.

import numpy as np
import matplotlib.pyplot as plt

g = 9.81
y0 = 20.0
v0 = 0.0
dt = 0.01
t_final = 2.0

t = np.arange(0, t_final + dt, dt)
y = np.zeros_like(t)
v = np.zeros_like(t)
y[0] = y0
v[0] = v0

for i in range(len(t) - 1):
    a = -g
    v[i + 1] = v[i] + a * dt
    y[i + 1] = y[i] + v[i] * dt

y_exact = y0 + v0 * t - 0.5 * g * t**2

plt.plot(t, y, label="Euler simulation")
plt.plot(t, y_exact, "--", label="Analytic solution")
plt.xlabel("Time (s)")
plt.ylabel("Height (m)")
plt.legend()
plt.grid(True)
plt.show()

Free-fall checklist: confirm the direction of gravity, use the same initial conditions in both solutions, stop the model when the object reaches the ground if that is part of the physical problem, and measure the largest difference between the two curves.

2. Projectile motion

For ideal projectile motion, ignore air resistance and separate horizontal and vertical motion. The horizontal acceleration is zero, while the vertical acceleration is -g. If the projectile starts at (x0, y0) with speed v0 and launch angle theta, its initial velocity components are:

vx = v0 cos(theta)
vy = v0 sin(theta)

import numpy as np
import matplotlib.pyplot as plt

v0 = 20.0
angle = np.deg2rad(45.0)
g = 9.81
dt = 0.01
t_final = 3.0

t = np.arange(0, t_final + dt, dt)
x = np.zeros_like(t)
y = np.zeros_like(t)
vx = np.zeros_like(t)
vy = np.zeros_like(t)

x[0], y[0] = 0.0, 0.0
vx[0] = v0 * np.cos(angle)
vy[0] = v0 * np.sin(angle)

for i in range(len(t) - 1):
    ax, ay = 0.0, -g
    vx[i + 1] = vx[i] + ax * dt
    vy[i + 1] = vy[i] + ay * dt
    x[i + 1] = x[i] + vx[i] * dt
    y[i + 1] = y[i] + vy[i] * dt

valid = y >= 0
plt.plot(x[valid], y[valid])
plt.xlabel("Horizontal position (m)")
plt.ylabel("Vertical position (m)")
plt.axis("equal")
plt.grid(True)
plt.show()

For a lab report, state the assumptions clearly: constant gravity, no drag, a point-like projectile, and a flat reference frame. If the plot continues below ground, use a mask or stop the integration at the first crossing. Do not silently interpret negative height as additional physical motion.

3. Simple harmonic motion

A mass on an ideal spring obeys:

d²x/dt² = -(k/m)x = -omega²x

where k is the spring constant, m is the mass, and omega = sqrt(k/m). The analytic solution for initial displacement A and zero initial velocity is:

x(t) = A cos(omega t)

import numpy as np
import matplotlib.pyplot as plt

m = 1.0
k = 4.0
omega = np.sqrt(k / m)
A = 0.5
dt = 0.01
t_final = 10.0

t = np.arange(0, t_final + dt, dt)
x = np.zeros_like(t)
v = np.zeros_like(t)
x[0] = A
v[0] = 0.0

for i in range(len(t) - 1):
    a = -(k / m) * x[i]
    v[i + 1] = v[i] + a * dt
    x[i + 1] = x[i] + v[i] * dt

x_exact = A * np.cos(omega * t)

plt.plot(t, x, label="Euler simulation")
plt.plot(t, x_exact, "--", label="Analytic solution")
plt.xlabel("Time (s)")
plt.ylabel("Displacement (m)")
plt.legend()
plt.grid(True)
plt.show()

The oscillator is an especially useful test because a basic Euler method can gradually gain or lose energy. If the simulated amplitude grows or shrinks noticeably while the analytic amplitude remains constant, the time step may be too large or the method may be unsuitable for the required accuracy. A velocity-Verlet or symplectic method is often a better next step for long-term mechanical simulations.

What to double-check

  • Initial conditions: Verify position and velocity at the first time index. A correct equation with incorrect starting values produces a consistently wrong trajectory.
  • Signs and coordinates: Write down which direction is positive before coding. Gravity, spring forces, and friction all depend on that convention.
  • Time-step resolution: Run the same model with dt, dt/2, and possibly dt/4. Important features should stabilize as the step decreases.
  • Units: Check that every parameter is compatible. For a spring, k/m must have units of inverse seconds squared.
  • Analytic comparison: Where an exact solution is available, calculate the pointwise error and the maximum absolute error rather than relying only on a visual plot.
  • Conservation laws: In ideal free fall, projectile motion, or an undamped oscillator, inspect energy or momentum where appropriate. Numerical drift is information about the method.
  • Plot labels: Include units, a legend, and a meaningful title. A graph is part of the result, not decoration.

A simple convergence test can be written as:

def max_error(dt):
    t = np.arange(0, 2.0 + dt, dt)
    y = np.zeros_like(t)
    v = np.zeros_like(t)
    y[0], v[0] = 20.0, 0.0
    g = 9.81

    for i in range(len(t) - 1):
        v[i + 1] = v[i] - g * dt
        y[i + 1] = y[i] + v[i] * dt

    exact = 20.0 - 0.5 * g * t**2
    return np.max(np.abs(y - exact))

for dt in [0.1, 0.05, 0.01]:
    print(dt, max_error(dt))

The precise error pattern depends on the update scheme and the problem, but decreasing error is a basic expectation for a well-behaved calculation over a fixed time interval.

Common mistakes

Updating position with the new velocity without noticing the change: This creates a different integration scheme. It is not automatically wrong, but you should identify the method and use it consistently.

Choosing a time step by appearance alone: A smooth graph can still be quantitatively inaccurate. Always compare multiple time steps or an analytic result.

Mixing degrees and radians: NumPy trigonometric functions use radians. Convert launch angles with np.deg2rad() when input is given in degrees.

Ignoring model boundaries: A projectile that has reached the ground should not continue as though the ground were absent. Decide how collisions or stopping conditions are represented.

Adding realism too early: Air resistance, variable gravity, friction, and collisions are worthwhile extensions, but begin with a model that has a known answer. A simple baseline makes debugging possible.

Confusing numerical and physical error: The difference between a simulation and an experiment may come from measurement uncertainty or omitted physics. The difference between a simulation and an analytic solution, under identical assumptions, is mainly a numerical-method question.

When to revisit

Return to this checklist whenever you change the physical model, parameter range, integration method, or Python environment. A script that behaves well for a short free-fall calculation may not be reliable for a long oscillation, a stiff spring, or a model with widely separated time scales.

Before using a simulation in a lab report or classroom resource, rerun the examples from a clean environment, confirm that NumPy and Matplotlib imports work, and check that the plots still show the intended comparison. If software packages receive major updates, verify the installation commands and test the code rather than assuming the output is unchanged.

Use this practical review sequence:

  1. Write the governing equation and assumptions in words.
  2. Choose units, initial conditions, and a sign convention.
  3. Run a short simulation with a deliberately small, easy-to-inspect data set.
  4. Repeat with smaller time steps and record the error or a conservation diagnostic.
  5. Compare with an analytic solution whenever one exists.
  6. Only then add features such as drag, collisions, damping, or parameter sweeps.

This workflow turns Python from a graphing tool into a physics laboratory: the code expresses the model, the plot reveals its behavior, and the checks tell you whether the numerical result deserves to be trusted.

Related Topics

#computational-physics#Python#simulations#numerical-methods#lab-resources
P

Physics Plus Editorial Team

Physics Education Editors

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.