Chapter 16
20 min read
Section 144 of 353

Motion in Space

Vector-Valued Functions

Learning Objectives

By the end of this section, you will be able to:

  1. Describe the motion of a particle in 3D space using position, velocity, and acceleration vectors
  2. Compute velocity as the derivative of the position vector function
  3. Calculate acceleration as the derivative of velocity (second derivative of position)
  4. Apply the fundamental kinematic equations to solve motion problems
  5. Analyze projectile motion, circular motion, and helical motion in 3D
  6. Connect Newton's laws to vector-valued functions
  7. Understand how motion equations are used in physics simulations and machine learning

The Big Picture: Why Study Motion in Space?

"The laws of motion were not discovered by looking at objects at rest. They were found by carefully analyzing how things change position over time."

Everything in the universe is in motion. Planets orbit stars, electrons swirl around nuclei, cars navigate highways, and robots traverse factory floors. To understand, predict, and control motion, we need a mathematical language that captures where an object is, how fast it's moving, and how its speed and direction are changing.

This is precisely what vector-valued functions and their derivatives provide. The position vector r(t)\mathbf{r}(t) tells us where an object is at any instant. Its derivative — the velocity vector — tells us the rate of change of position. The second derivative — acceleration — tells us how the velocity itself is changing.

🚀 Aerospace

  • Satellite trajectory calculation
  • Rocket launch dynamics
  • Aircraft autopilot systems
  • Interplanetary mission planning

🤖 Robotics

  • Robot arm motion planning
  • Drone navigation and control
  • Autonomous vehicle trajectory
  • Manipulation task planning

🎮 Games & Graphics

  • Physics engine simulation
  • Character and camera motion
  • Particle system dynamics
  • Realistic projectile physics

🧠 Machine Learning

  • Reinforcement learning physics environments
  • Neural physics engines
  • Motion prediction models
  • Differentiable simulators

The Core Relationship

The relationship between position, velocity, and acceleration is the foundation of classical mechanics:

Position → (derivative) → Velocity → (derivative) → Acceleration
Acceleration → (integral) → Velocity → (integral) → Position

Historical Origins: From Galileo to Newton

The mathematical description of motion evolved over centuries, reaching its modern form through the work of several brilliant minds.

Galileo Galilei (1564–1642)

Galileo revolutionized our understanding of motion through careful experiments. He showed that in the absence of air resistance, objects fall with constant acceleration, regardless of their mass. His analysis of projectile motion decomposed it into independent horizontal and vertical components — a key insight that persists today.

Isaac Newton (1643–1727)

Newton unified terrestrial and celestial mechanics with his three laws of motion and the law of universal gravitation. His invention of calculus (simultaneously with Leibniz) provided the mathematical tools to describe motion precisely:

  • First Law: An object in motion stays in motion unless acted upon by a force (velocity is constant when net force is zero)
  • Second Law: F=ma\mathbf{F} = m\mathbf{a} — force equals mass times acceleration
  • Third Law: For every action, there is an equal and opposite reaction

Calculus Was Invented for Physics

Newton developed calculus specifically to solve problems in mechanics. The derivatives and integrals we study are the same tools he used to describe planetary orbits and falling objects over 300 years ago.


Position as a Vector Function of Time

A particle moving through 3D space has a position that changes with time. We describe this using a vector-valued function of a single variable tt (time):

Position Vector

r(t)=x(t)i+y(t)j+z(t)k=x(t),y(t),z(t)\mathbf{r}(t) = x(t)\,\mathbf{i} + y(t)\,\mathbf{j} + z(t)\,\mathbf{k} = \langle x(t), y(t), z(t) \rangle

where x(t)x(t), y(t)y(t), and z(t)z(t) are the component functions giving the particle's coordinates at time tt.

The position vector r(t)\mathbf{r}(t) points from the origin to the particle's location. As tt changes, the tip of this vector traces out the particle's trajectory or path through space.

Example: Helical Motion

Consider a particle moving along a helix:

r(t)=3cost,3sint,2t\mathbf{r}(t) = \langle 3\cos t, 3\sin t, 2t \rangle

This traces a spiral path. The xx and yy components describe circular motion of radius 3, while the zz component increases linearly, creating the helical shape.

Time tx(t) = 3cos ty(t) = 3sin tz(t) = 2tPosition
0300(3, 0, 0)
π/203π(0, 3, π)
π-30(-3, 0, 2π)
3π/20-3(0, -3, 3π)
30(3, 0, 4π)

Velocity: The Derivative of Position

The velocity vector measures how quickly the position is changing and in what direction. It is the derivative of the position vector:

Velocity Vector

v(t)=drdt=r(t)=x(t),y(t),z(t)\mathbf{v}(t) = \frac{d\mathbf{r}}{dt} = \mathbf{r}'(t) = \langle x'(t), y'(t), z'(t) \rangle

Geometrically, the velocity vector is tangent to the path at each point. Its magnitude v(t)|\mathbf{v}(t)| is the speed — how fast the particle is moving.

Example: Velocity of Helical Motion

For r(t)=3cost,3sint,2t\mathbf{r}(t) = \langle 3\cos t, 3\sin t, 2t \rangle:

v(t)=r(t)=3sint,3cost,2\mathbf{v}(t) = \mathbf{r}'(t) = \langle -3\sin t, 3\cos t, 2 \rangle

The speed is:

v(t)=9sin2t+9cos2t+4=9+4=13|\mathbf{v}(t)| = \sqrt{9\sin^2 t + 9\cos^2 t + 4} = \sqrt{9 + 4} = \sqrt{13}

Constant Speed Along a Helix

Notice that the speed 13\sqrt{13} is constant — it doesn't depend on tt. The particle moves at uniform speed even though its direction is constantly changing.

Key Properties of Velocity

  1. Direction: Velocity points in the direction of motion (tangent to path)
  2. Magnitude: Speed =v(t)=x(t)2+y(t)2+z(t)2= |\mathbf{v}(t)| = \sqrt{x'(t)^2 + y'(t)^2 + z'(t)^2}
  3. Units: Length per time (m/s, km/h, etc.)

Acceleration: The Second Derivative

The acceleration vector measures how quickly the velocity is changing:

Acceleration Vector

a(t)=dvdt=v(t)=r(t)=x(t),y(t),z(t)\mathbf{a}(t) = \frac{d\mathbf{v}}{dt} = \mathbf{v}'(t) = \mathbf{r}''(t) = \langle x''(t), y''(t), z''(t) \rangle

Acceleration can change either the speed (magnitude of velocity) or the direction of velocity — or both. Even an object moving at constant speed can have non-zero acceleration if its direction is changing (like in circular motion).

Example: Acceleration of Helical Motion

For v(t)=3sint,3cost,2\mathbf{v}(t) = \langle -3\sin t, 3\cos t, 2 \rangle:

a(t)=v(t)=3cost,3sint,0\mathbf{a}(t) = \mathbf{v}'(t) = \langle -3\cos t, -3\sin t, 0 \rangle

Notice that the acceleration:

  • Has no vertical component (no change in vertical velocity)
  • Points toward the zz-axis (center of the helix)
  • Has constant magnitude a(t)=9cos2t+9sin2t=3|\mathbf{a}(t)| = \sqrt{9\cos^2 t + 9\sin^2 t} = 3

Acceleration Points Toward Curvature

For a particle moving along a curved path, acceleration always has a component pointing toward the "inside" of the curve. This is what makes the path bend. We'll explore this in detail in the section on the TNB frame.


The Fundamental Kinematic Equations

When acceleration is constant, we can integrate to find simple formulas for velocity and position. These are the kinematic equations that appear throughout physics and engineering.

Constant Acceleration Kinematics (Vector Form)

Given constant acceleration a\mathbf{a}, initial velocity v0\mathbf{v}_0, and initial position r0\mathbf{r}_0:

v(t)=v0+at\mathbf{v}(t) = \mathbf{v}_0 + \mathbf{a}t(velocity)
r(t)=r0+v0t+12at2\mathbf{r}(t) = \mathbf{r}_0 + \mathbf{v}_0 t + \frac{1}{2}\mathbf{a}t^2(position)

Deriving the Equations

These equations come directly from integration:

  1. Start with constant acceleration: a(t)=a\mathbf{a}(t) = \mathbf{a} (constant)
  2. Integrate to get velocity: v(t)=adt=at+C1\mathbf{v}(t) = \int \mathbf{a}\,dt = \mathbf{a}t + \mathbf{C}_1
  3. Apply initial condition v(0)=v0\mathbf{v}(0) = \mathbf{v}_0: C1=v0\mathbf{C}_1 = \mathbf{v}_0
  4. Integrate again for position: r(t)=v(t)dt=v0t+12at2+C2\mathbf{r}(t) = \int \mathbf{v}(t)\,dt = \mathbf{v}_0 t + \frac{1}{2}\mathbf{a}t^2 + \mathbf{C}_2
  5. Apply initial condition r(0)=r0\mathbf{r}(0) = \mathbf{r}_0: C2=r0\mathbf{C}_2 = \mathbf{r}_0

Component Form

These vector equations can be written component-by-component. For example, the xx-component of position is:

x(t)=x0+v0xt+12axt2x(t) = x_0 + v_{0x}t + \frac{1}{2}a_x t^2

Similarly for yy and zz.


Projectile Motion in 3D

Projectile motion is one of the most important applications of motion in space. Near Earth's surface (ignoring air resistance), the only force is gravity, giving constant downward acceleration.

3D Projectile Motion

With a=(0,0,g)\mathbf{a} = (0, 0, -g) and initial velocity v0=(v0cosθcosϕ,v0cosθsinϕ,v0sinθ)\mathbf{v}_0 = (v_0\cos\theta\cos\phi, v_0\cos\theta\sin\phi, v_0\sin\theta):

x(t)=v0cosθcosϕtx(t) = v_0 \cos\theta \cos\phi \cdot t
y(t)=v0cosθsinϕty(t) = v_0 \cos\theta \sin\phi \cdot t
z(t)=v0sinθt12gt2z(t) = v_0 \sin\theta \cdot t - \frac{1}{2}gt^2

where θ\theta is the elevation angle and ϕ\phi is the azimuth angle.

Key Projectile Motion Results

QuantityFormulaDescription
Time of flightT = 2v₀sin(θ)/gTotal time in air (landing at same height)
Maximum heightH = v₀²sin²(θ)/(2g)Highest point reached
RangeR = v₀²sin(2θ)/gHorizontal distance (2D, same height landing)
Speed at apexv = v₀cos(θ)Only horizontal component remains

Interactive: 3D Projectile Motion Analyzer

Loading 3D visualization...

Circular and Helical Motion

Uniform Circular Motion

When a particle moves in a circle at constant speed, its position vector traces a circular path. Despite constant speed, the particle is accelerating because its direction is constantly changing.

Uniform Circular Motion

For a circle of radius RR with angular velocity ω\omega:

Position: r(t)=Rcos(ωt),sin(ωt),0\mathbf{r}(t) = R\langle \cos(\omega t), \sin(\omega t), 0 \rangle
Velocity: v(t)=Rωsin(ωt),cos(ωt),0\mathbf{v}(t) = R\omega\langle -\sin(\omega t), \cos(\omega t), 0 \rangle
Acceleration: a(t)=Rω2cos(ωt),sin(ωt),0=ω2r(t)\mathbf{a}(t) = -R\omega^2\langle \cos(\omega t), \sin(\omega t), 0 \rangle = -\omega^2 \mathbf{r}(t)

Key observations about circular motion:

  • Speed is constant: v=Rω|\mathbf{v}| = R\omega
  • Velocity is perpendicular to position: vr=0\mathbf{v} \cdot \mathbf{r} = 0
  • Acceleration points toward center: a=ω2r\mathbf{a} = -\omega^2 \mathbf{r} (centripetal)
  • Centripetal acceleration magnitude: a=Rω2=v2/R|\mathbf{a}| = R\omega^2 = v^2/R

Helical Motion

A helix combines circular motion with linear motion along the axis. This describes the path of charged particles in magnetic fields, DNA molecules, spiral staircases, and many other phenomena.

Helical Motion

Position: r(t)=Acos(ωt),Asin(ωt),kt\mathbf{r}(t) = \langle A\cos(\omega t), A\sin(\omega t), kt \rangle
Velocity: v(t)=Aωsin(ωt),Aωcos(ωt),k\mathbf{v}(t) = \langle -A\omega\sin(\omega t), A\omega\cos(\omega t), k \rangle
Speed: v=A2ω2+k2|\mathbf{v}| = \sqrt{A^2\omega^2 + k^2} (constant!)

Interactive: Motion Types Explorer

Loading 3D visualization...

Newton's Laws in Vector Form

Newton's second law connects motion to forces. In vector form, it provides the bridge between calculus and physics:

Newton's Second Law (Vector Form)

Fnet=ma=mdvdt=md2rdt2\mathbf{F}_{net} = m\mathbf{a} = m\frac{d\mathbf{v}}{dt} = m\frac{d^2\mathbf{r}}{dt^2}

The net force on an object equals its mass times its acceleration vector. This is a vector equation — it applies component by component.

Implications for Motion Analysis

  1. Force determines acceleration: Given the forces acting on an object, we can find its acceleration by dividing by mass
  2. Acceleration determines trajectory: By integrating acceleration twice, we get velocity and then position
  3. Initial conditions matter: The integration constants come from knowing the initial position and velocity

Example: Charged Particle in a Magnetic Field

A charged particle moving in a magnetic field experiences a force F=qv×B\mathbf{F} = q\mathbf{v} \times \mathbf{B}. If the magnetic field is uniform and along the zz-axis, this creates circular motion in the xyxy-plane — exactly the motion we analyzed above.

Non-Constant Forces

When forces depend on position or velocity (like air resistance or springs), the differential equations become more complex. Often we need numerical methods to solve them — this is where computational physics and machine learning come in.


Applications in Physics and Engineering

1. Spacecraft Navigation

Space agencies use these exact equations to plan missions. The position, velocity, and acceleration of spacecraft must be tracked precisely. Gravitational forces from multiple bodies create complex trajectories that require numerical integration.

2. Sports Physics

Analyzing the trajectory of balls (with spin, air resistance, and Magnus effect) helps athletes and coaches optimize performance. The basic projectile motion equations are the starting point, with corrections for real-world effects.

3. Particle Accelerators

The Large Hadron Collider guides particles using precisely calculated magnetic fields. The motion equations tell engineers exactly what fields are needed to bend particle paths into the desired circular trajectory.

4. Computer Animation

Physics engines in films and games use these equations to create realistic motion. When you see a character jump or a ball bounce in a movie, the animation is often driven by kinematic equations running in real-time.


Machine Learning Connections

The mathematical framework of motion in space directly connects to several areas of modern machine learning:

1. Physics-Informed Neural Networks (PINNs)

PINNs encode physical laws (like F=ma\mathbf{F} = m\mathbf{a}) directly into neural network loss functions. The network learns to predict trajectories while respecting conservation laws and kinematic constraints.

2. Differentiable Physics Simulators

Modern physics engines can compute gradients through the simulation. This enables:

  • Gradient-based control: Learn optimal control policies by backpropagating through physics
  • System identification: Learn physical parameters (mass, friction) from observations
  • Trajectory optimization: Find optimal paths through differentiable simulation

3. Neural ODEs

Neural Ordinary Differential Equations (Chen et al., 2018) parameterize the derivative function with a neural network:

dhdt=fθ(h,t)\frac{d\mathbf{h}}{dt} = f_\theta(\mathbf{h}, t)

This is exactly the structure of our motion equations, where h=[r,v]\mathbf{h} = [\mathbf{r}, \mathbf{v}] is the state and ff describes the physics. Neural ODEs learn the dynamics from data.

4. Reinforcement Learning Environments

Many RL benchmarks (MuJoCo, PyBullet, Isaac Gym) are physics simulations governed by these equations. RL agents learn to control systems by understanding (implicitly) the relationship between forces and motion.

The Power of Calculus in ML

The chain rule that lets us differentiate r(t)\mathbf{r}(t) to get velocity is the same chain rule that enables backpropagation in neural networks. Understanding motion calculus deepens your understanding of why deep learning works.


Python Implementation

Projectile Motion Simulation

3D Projectile Motion Simulation
🐍projectile_motion.py
5Position Vector Function

The position r(t) = (x(t), y(t), z(t)) describes where the particle is at any time t. This is a vector-valued function of one variable.

25Velocity from Differentiation

Velocity v(t) = r'(t) = (x'(t), y'(t), z'(t)). In projectile motion, vx and vy are constant (no horizontal forces), while vz changes linearly due to gravity.

32Constant Acceleration

In free fall, acceleration a(t) = r''(t) = (0, 0, -g) is constant. This is Newton's second law applied: F = ma, where F = mg downward.

55Speed Calculation

Speed |v(t)| = √(vx² + vy² + vz²) is the magnitude of velocity. Speed is minimum at the apex where vz = 0.

95 lines without explanation
1import numpy as np
2import matplotlib.pyplot as plt
3from mpl_toolkits.mplot3d import Axes3D
4
5def projectile_motion_3d(v0, theta, phi, g=9.8, dt=0.01):
6    """
7    Simulate 3D projectile motion.
8
9    Parameters:
10    - v0: Initial speed (m/s)
11    - theta: Elevation angle from horizontal (degrees)
12    - phi: Azimuth angle in xy-plane (degrees)
13    - g: Gravitational acceleration (m/s²)
14    - dt: Time step (s)
15
16    Returns position r(t), velocity v(t), acceleration a(t)
17    """
18    # Convert angles to radians
19    theta_rad = np.radians(theta)
20    phi_rad = np.radians(phi)
21
22    # Initial velocity components
23    v0x = v0 * np.cos(theta_rad) * np.cos(phi_rad)
24    v0y = v0 * np.cos(theta_rad) * np.sin(phi_rad)
25    v0z = v0 * np.sin(theta_rad)
26
27    # Time of flight (until z = 0)
28    t_flight = 2 * v0z / g
29    t = np.arange(0, t_flight, dt)
30
31    # Position: r(t) = r₀ + v₀t + ½at²
32    x = v0x * t
33    y = v0y * t
34    z = v0z * t - 0.5 * g * t**2
35
36    # Velocity: v(t) = v₀ + at
37    vx = np.full_like(t, v0x)
38    vy = np.full_like(t, v0y)
39    vz = v0z - g * t
40
41    # Acceleration: a(t) = constant
42    ax = np.zeros_like(t)
43    ay = np.zeros_like(t)
44    az = np.full_like(t, -g)
45
46    return {
47        't': t,
48        'position': np.column_stack([x, y, z]),
49        'velocity': np.column_stack([vx, vy, vz]),
50        'acceleration': np.column_stack([ax, ay, az])
51    }
52
53# Example: Launch at 20 m/s, 45° elevation, 30° azimuth
54result = projectile_motion_3d(v0=20, theta=45, phi=30)
55
56# Compute derived quantities
57speeds = np.linalg.norm(result['velocity'], axis=1)
58max_height_idx = np.argmax(result['position'][:, 2])
59max_height = result['position'][max_height_idx, 2]
60range_dist = np.linalg.norm(result['position'][-1, :2])
61
62print("Projectile Motion Analysis")
63print("=" * 40)
64print(f"Time of flight: {result['t'][-1]:.2f} s")
65print(f"Maximum height: {max_height:.2f} m")
66print(f"Horizontal range: {range_dist:.2f} m")
67print(f"Initial speed: {speeds[0]:.2f} m/s")
68print(f"Speed at apex: {speeds[max_height_idx]:.2f} m/s")
69print(f"Final speed: {speeds[-1]:.2f} m/s")
70
71# Visualize
72fig = plt.figure(figsize=(12, 5))
73
74# 3D trajectory
75ax1 = fig.add_subplot(121, projection='3d')
76ax1.plot(*result['position'].T, 'b-', linewidth=2)
77ax1.scatter(*result['position'][0], c='green', s=100, label='Start')
78ax1.scatter(*result['position'][-1], c='red', s=100, label='End')
79ax1.scatter(*result['position'][max_height_idx], c='purple',
80            s=100, label='Apex')
81ax1.set_xlabel('X (m)')
82ax1.set_ylabel('Y (m)')
83ax1.set_zlabel('Z (m)')
84ax1.set_title('3D Projectile Trajectory')
85ax1.legend()
86
87# Speed vs time
88ax2 = fig.add_subplot(122)
89ax2.plot(result['t'], speeds, 'b-', linewidth=2)
90ax2.axhline(y=speeds[max_height_idx], color='purple',
91            linestyle='--', label='Speed at apex')
92ax2.set_xlabel('Time (s)')
93ax2.set_ylabel('Speed (m/s)')
94ax2.set_title('Speed vs Time')
95ax2.legend()
96ax2.grid(True, alpha=0.3)
97
98plt.tight_layout()
99plt.show()

Circular and Helical Motion

Circular and Helical Motion Analysis
🐍circular_helix.py
15Circular Motion Parametrization

r(t) = (R cos(ωt), R sin(ωt), 0) traces a circle of radius R with angular velocity ω. The period is T = 2π/ω.

24Velocity Perpendicular to Position

For circular motion, v(t) · r(t) = 0 always. The velocity is tangent to the circle, perpendicular to the radius vector.

30Centripetal Acceleration

a(t) = -ω²r(t) points toward the center. The magnitude |a| = Rω² = v²/R is the centripetal acceleration formula.

47Helix: Circular + Linear

A helix combines circular motion in the xy-plane with constant vertical velocity. The DNA double helix and spiral staircases follow this curve.

109 lines without explanation
1import numpy as np
2import matplotlib.pyplot as plt
3
4def circular_motion(R, omega, t_max=10, dt=0.01):
5    """
6    Uniform circular motion in the xy-plane.
7
8    Parameters:
9    - R: Radius of circular path (m)
10    - omega: Angular velocity (rad/s)
11    - t_max: Maximum simulation time (s)
12
13    The position vector traces a circle:
14    r(t) = (R cos(ωt), R sin(ωt), 0)
15    """
16    t = np.arange(0, t_max, dt)
17
18    # Position: r(t) = R(cos(ωt), sin(ωt), 0)
19    x = R * np.cos(omega * t)
20    y = R * np.sin(omega * t)
21    z = np.zeros_like(t)
22
23    # Velocity: v(t) = r'(t) = Rω(-sin(ωt), cos(ωt), 0)
24    # Note: v is perpendicular to r (tangent to circle)
25    vx = -R * omega * np.sin(omega * t)
26    vy = R * omega * np.cos(omega * t)
27    vz = np.zeros_like(t)
28
29    # Acceleration: a(t) = r''(t) = -Rω²(cos(ωt), sin(ωt), 0)
30    # Note: a = -ω²r points toward the center (centripetal)
31    ax = -R * omega**2 * np.cos(omega * t)
32    ay = -R * omega**2 * np.sin(omega * t)
33    az = np.zeros_like(t)
34
35    return {
36        't': t,
37        'position': np.column_stack([x, y, z]),
38        'velocity': np.column_stack([vx, vy, vz]),
39        'acceleration': np.column_stack([ax, ay, az])
40    }
41
42def helix_motion(A, omega, k, t_max=10, dt=0.01):
43    """
44    Helical motion: circular motion with constant upward velocity.
45
46    r(t) = (A cos(ωt), A sin(ωt), kt)
47
48    This combines circular motion in xy with linear motion in z.
49    """
50    t = np.arange(0, t_max, dt)
51
52    # Position: spiral upward
53    x = A * np.cos(omega * t)
54    y = A * np.sin(omega * t)
55    z = k * t
56
57    # Velocity: tangent to helix
58    vx = -A * omega * np.sin(omega * t)
59    vy = A * omega * np.cos(omega * t)
60    vz = np.full_like(t, k)  # Constant upward velocity
61
62    # Acceleration: centripetal (horizontal only)
63    ax = -A * omega**2 * np.cos(omega * t)
64    ay = -A * omega**2 * np.sin(omega * t)
65    az = np.zeros_like(t)  # No vertical acceleration
66
67    return {
68        't': t,
69        'position': np.column_stack([x, y, z]),
70        'velocity': np.column_stack([vx, vy, vz]),
71        'acceleration': np.column_stack([ax, ay, az])
72    }
73
74# Compare circular and helical motion
75circular = circular_motion(R=3, omega=1.5, t_max=6)
76helix = helix_motion(A=3, omega=1.5, k=1, t_max=6)
77
78fig = plt.figure(figsize=(14, 5))
79
80# Circular motion
81ax1 = fig.add_subplot(131, projection='3d')
82ax1.plot(*circular['position'].T, 'b-', linewidth=2)
83ax1.set_title('Circular Motion')
84ax1.set_xlabel('X')
85ax1.set_ylabel('Y')
86ax1.set_zlabel('Z')
87
88# Helical motion
89ax2 = fig.add_subplot(132, projection='3d')
90ax2.plot(*helix['position'].T, 'r-', linewidth=2)
91ax2.set_title('Helical Motion')
92ax2.set_xlabel('X')
93ax2.set_ylabel('Y')
94ax2.set_zlabel('Z')
95
96# Speed comparison
97ax3 = fig.add_subplot(133)
98circular_speed = np.linalg.norm(circular['velocity'], axis=1)
99helix_speed = np.linalg.norm(helix['velocity'], axis=1)
100ax3.plot(circular['t'], circular_speed, 'b-', label='Circular')
101ax3.plot(helix['t'], helix_speed, 'r-', label='Helix')
102ax3.set_xlabel('Time (s)')
103ax3.set_ylabel('Speed (m/s)')
104ax3.set_title('Speed: Constant for Both!')
105ax3.legend()
106ax3.grid(True, alpha=0.3)
107
108plt.tight_layout()
109plt.show()
110
111# Key insight: Both have constant speed!
112print("Circular motion speed:", circular_speed[0], "(constant)")
113print("Helix motion speed:", helix_speed[0], "(constant)")

Physics Engine for ML Applications

Physics Simulation for Machine Learning
🐍physics_engine.py
9Physics Engines in ML

Modern ML uses physics simulations for training robots (RL), generating synthetic data, and learning physical laws from observations (neural physics engines).

22State Space Representation

The state [r, v] = [x, y, z, vx, vy, vz] fully describes the system. Neural networks in physics learn to predict state evolution.

33Force Accumulation

Multiple forces combine: gravity + drag + external forces. Physics-informed neural networks (PINNs) learn to predict these forces from data.

48ODE Integration

scipy.odeint numerically solves r''(t) = F/m. Neural ODEs (Chen et al., 2018) learn the right-hand side from data.

121 lines without explanation
1import numpy as np
2from scipy.integrate import odeint
3import matplotlib.pyplot as plt
4
5class PhysicsSimulator:
6    """
7    Physics engine for ML applications.
8
9    This demonstrates how calculus-based motion equations
10    are used in physics simulations, reinforcement learning
11    environments, and neural physics engines.
12    """
13
14    def __init__(self, mass=1.0, drag_coef=0.1):
15        self.mass = mass
16        self.drag = drag_coef
17        self.g = np.array([0, 0, -9.8])
18
19    def derivatives(self, state, t, force_fn=None):
20        """
21        Compute dr/dt and dv/dt given current state.
22
23        state = [x, y, z, vx, vy, vz]
24
25        Newton's 2nd law: m(dv/dt) = F_net
26        Kinematics: dr/dt = v
27        """
28        pos = state[:3]
29        vel = state[3:]
30
31        # Forces: gravity + drag + external
32        F_gravity = self.mass * self.g
33        F_drag = -self.drag * np.linalg.norm(vel) * vel
34        F_external = force_fn(pos, vel, t) if force_fn else np.zeros(3)
35
36        F_net = F_gravity + F_drag + F_external
37
38        # Newton's 2nd law: a = F/m
39        acc = F_net / self.mass
40
41        # Return [dr/dt, dv/dt] = [v, a]
42        return np.concatenate([vel, acc])
43
44    def simulate(self, r0, v0, t_span, force_fn=None):
45        """
46        Integrate equations of motion using scipy.
47
48        This is essentially solving:
49        r''(t) = F(r, r', t) / m
50        """
51        state0 = np.concatenate([r0, v0])
52        t = np.linspace(0, t_span, 500)
53
54        solution = odeint(
55            self.derivatives,
56            state0,
57            t,
58            args=(force_fn,)
59        )
60
61        return {
62            't': t,
63            'position': solution[:, :3],
64            'velocity': solution[:, 3:]
65        }
66
67# Example 1: Ball with air resistance
68sim = PhysicsSimulator(mass=0.5, drag_coef=0.05)
69r0 = np.array([0., 0., 0.])
70v0 = np.array([10., 5., 15.])
71
72result_drag = sim.simulate(r0, v0, t_span=4)
73
74# Example 2: Same ball, no drag (for comparison)
75sim_no_drag = PhysicsSimulator(mass=0.5, drag_coef=0.0)
76result_no_drag = sim_no_drag.simulate(r0, v0, t_span=4)
77
78# Visualize the difference
79fig = plt.figure(figsize=(12, 5))
80
81ax1 = fig.add_subplot(121, projection='3d')
82ax1.plot(*result_drag['position'].T, 'b-',
83         linewidth=2, label='With drag')
84ax1.plot(*result_no_drag['position'].T, 'r--',
85         linewidth=2, label='No drag')
86ax1.set_xlabel('X (m)')
87ax1.set_ylabel('Y (m)')
88ax1.set_zlabel('Z (m)')
89ax1.set_title('Trajectory: Air Resistance Effect')
90ax1.legend()
91
92ax2 = fig.add_subplot(122)
93speed_drag = np.linalg.norm(result_drag['velocity'], axis=1)
94speed_no_drag = np.linalg.norm(result_no_drag['velocity'], axis=1)
95ax2.plot(result_drag['t'], speed_drag, 'b-', label='With drag')
96ax2.plot(result_no_drag['t'], speed_no_drag, 'r--', label='No drag')
97ax2.set_xlabel('Time (s)')
98ax2.set_ylabel('Speed (m/s)')
99ax2.set_title('Speed vs Time')
100ax2.legend()
101ax2.grid(True, alpha=0.3)
102
103plt.tight_layout()
104plt.show()
105
106# ML Application: Predicting trajectory from partial observation
107print("\nML Application: Motion Prediction")
108print("=" * 40)
109print("Given: First 0.5s of observations")
110print("Task: Predict position at t=2s")
111
112# Extract training data (first 0.5 seconds)
113train_mask = result_drag['t'] <= 0.5
114train_t = result_drag['t'][train_mask]
115train_pos = result_drag['position'][train_mask]
116
117# True position at t=2s
118idx_2s = np.argmin(np.abs(result_drag['t'] - 2.0))
119true_pos_2s = result_drag['position'][idx_2s]
120
121# Simple physics-informed prediction (use learned drag)
122# In real ML, we'd train a neural network on this
123print(f"\nTrue position at t=2s: {true_pos_2s}")
124print("A neural network could learn the drag coefficient")
125print("from observations and make accurate predictions!")

Test Your Understanding


Summary

Motion in space is described by vector-valued functions and their derivatives. The position vector tells us where, velocity tells us how fast and which direction, and acceleration tells us how velocity is changing.

Key Concepts

ConceptDefinitionFormula
PositionLocation at time tr(t) = ⟨x(t), y(t), z(t)⟩
VelocityRate of change of positionv(t) = r'(t)
SpeedMagnitude of velocity|v(t)| = √(x'² + y'² + z'²)
AccelerationRate of change of velocitya(t) = v'(t) = r''(t)
Constant accelerationPosition formular(t) = r₀ + v₀t + ½at²

Key Takeaways

  1. Velocity is the derivative of position: v(t)=r(t)\mathbf{v}(t) = \mathbf{r}'(t)
  2. Acceleration is the derivative of velocity: a(t)=v(t)=r(t)\mathbf{a}(t) = \mathbf{v}'(t) = \mathbf{r}''(t)
  3. Velocity is tangent to the path at every point
  4. Constant speed doesn't mean zero acceleration: curved paths require centripetal acceleration
  5. Newton's second law connects force to acceleration: F=ma\mathbf{F} = m\mathbf{a}
  6. Initial conditions (r₀ and v₀) are essential for solving motion problems
  7. These concepts are foundational for physics simulations in robotics, games, and machine learning
The Calculus of Motion:
"Position, velocity, acceleration — three vectors connected by differentiation, describing every motion from falling apples to orbiting planets."
Coming Next: In the next section, we'll explore the TNB Frame — the tangent, normal, and binormal vectors that form a natural coordinate system moving along with a particle. This will give us deeper insight into curvature and torsion of space curves.
Loading comments...