Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 47 ยท Getting Started

Python and NumPy for Physics

Learn the NumPy skills every simulation needs: arrays, linspace, vectorized formulas, slicing, masks, broadcasting and physical constants, with runnable physics examples.

A simulation is mostly arithmetic on long lists of numbers: positions of particles, values of a field on a grid, samples of a signal. Python on its own handles lists slowly and awkwardly. NumPy adds the array, a block of numbers of one type that supports math on all elements at once. Nearly every scientific Python tool (SciPy, Matplotlib, pandas) is built on it.

This lesson gives you the small set of NumPy skills used in the rest of the course.

An array of times multiplied by 9.8 to give an array of speeds, with an anatomy card
One expression, v = 9.8 * t, updates every element. No loop is written.

What you will learn

  • Create arrays with np.array, np.linspace, np.arange and np.zeros.
  • Write vectorized formulas instead of loops.
  • Select data with slices and boolean masks.
  • Combine arrays of different shapes with broadcasting.
  • Use physical constants from scipy.constants.

Key terms

Array: a fixed-size grid of numbers of one type (ndarray).

Shape: the size along each axis, for example (100,) or (50, 50).

Vectorization: writing one expression that acts on whole arrays.

Mask: a boolean array that selects the elements where a condition is true.

Broadcasting: the rule that stretches smaller arrays to match larger ones.

Creating arrays

The most useful constructors for physics are these.

  • np.array([1.0, 2.5, 4.0]) builds an array from a list.
  • np.linspace(a, b, n) gives n evenly spaced points from a to b including b. Use it for a time axis or a spatial grid.
  • np.arange(a, b, step) steps by a fixed amount and excludes b. Rounding can make the last point surprising for float steps, so prefer linspace for floats.
  • np.zeros(n) and np.ones(n) make arrays to fill later.

Each array has a shape and a dtype. Scientific work uses float64 almost always: about 16 significant decimal digits.

Vectorized formulas

A formula that you write for a single number works unchanged on an array. For free fall from height y0:

y = y0 - g tยฒ / 2, v = -g t

Writing y = y0 - 0.5 * g * t**2 with t an array computes the height at every instant. The loop runs inside NumPy, in compiled code, which is typically tens of times faster than a Python for loop.

Python Vectorized free fall

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Slicing and masks

Indexing starts at 0. A slice a[start:stop] includes start and excludes stop; a[::2] takes every second element, and a[-1] is the last. Slices are views: changing a slice changes the original array too.

Masks select by condition. t[y > 0] keeps the times where the height is positive. Conditions combine with & (and), | (or) and ~ (not), each condition in parentheses.

Slices matter a lot in simulations. For instance, u[1:] - u[:-1] is the difference between each point and its left neighbor, which is the heart of a finite-difference derivative (chapter 2).

Reductions

Functions such as sum, mean, max, min, std and cumsum collapse or accumulate an array. With a 2D array you choose the axis: a.sum(axis=0) adds down columns, a.sum(axis=1) adds along rows.

Example: the kinetic energy of N particles of mass m with speeds v is 0.5 * m * (v**2).sum().

Broadcasting

Broadcasting lets arrays of different shapes work together. A column of shape (3, 1) and a row of shape (1, 4) combine into a (3, 4) table:

Python
x = np.array([[0.], [1.], [2.]])     # shape (3, 1)
y = np.array([[0., 1., 2., 3.]])     # shape (1, 4)
r2 = x**2 + y**2                     # shape (3, 4)

The rule: compare shapes from the right; two sizes are compatible if they are equal or one of them is 1. This is how you build a 2D field from two 1D axes, with no loops.

Python Potential of two point charges on a grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Constants and units

Typing 8.99e9 by hand invites mistakes. scipy.constants provides CODATA values with their SI units: c (speed of light, 299 792 458 m/s), h, hbar, e, k (Boltzmann, in J/K), G, epsilon_0, m_e, g (standard gravity, 9.80665 m/sยฒ). Work in SI units inside your program and convert only when printing.

Python Constants and a sanity check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common misconceptions

"A slice is a copy." It is a view. b = a[2:5]; b[0] = 99 also changes a. Use a[2:5].copy() when you need independence.

"arange and linspace are interchangeable." arange(0, 1, 0.1) excludes 1 and, with float steps, may produce an extra or missing end point. linspace(0, 1, 11) always gives exactly 11 points ending at 1.

"Loops are fine because the computer is fast." For large grids a Python loop is much slower than a vectorized expression. Write clear vector code first; loops are for logic that truly cannot be vectorized.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does np.linspace(0, 2, 5) return?

    linspace includes both ends and spaces five points evenly: step (2 - 0) / (5 - 1) = 0.5.
  2. 2. If t is an array, which line computes the height of a dropped object at all times?

    The ordinary formula, written with array operations, acts on every element at once.
  3. 3. An array a has shape (4, 1) and b has shape (1, 5). What is the shape of a + b?

    Broadcasting stretches the size-1 axes: (4, 1) with (1, 5) gives (4, 5).
  4. 4. You write b = a[1:4] and then set b[0] = 0. What happens to a?

    Basic slices share memory with the original array. Call .copy() to detach.
  5. 5. Why use scipy.constants instead of typing values by hand?

    A named, standard constant avoids typos and keeps units consistent.

Summary

  • NumPy arrays hold numbers of one type and apply math to every element at once.
  • linspace builds grids that include the end point; arange excludes it.
  • Slices are views and masks select by condition.
  • Broadcasting builds 2D fields from 1D axes without loops.
  • Take constants from scipy.constants and keep SI units inside the program.

Next: Plotting Physics Data