Lesson
10: NumPy Arrays — Vectorized Math 50x Faster Than
Loops
The “Boring Stuff” Problem: Slow Element-by-Element Python Lists
Standard Python lists are flexible—a single list can hold
"AISI-4140", 25, and True side by
side. That flexibility makes mathematical array loops slow because
Python must inspect the data type of every single item on
every loop step. Even worse, you cannot add
two Python lists elementwise ([1, 2] + [3, 4] glues them
into [1, 2, 3, 4] instead of [4, 6]!).
NumPy (ndarray) fixes
both. Think of a NumPy array as a continuous, tight block of
identical numerical cells in C memory:
- Vectorized Operations: Write
sigma = E * epsONCE—it automatically multiplies 10 elements or 10,000,000 strain measurements simultaneously with zeroforloops! - Broadcasting: Subtract scalar ambient
T_nodes - 300.0, or scale every row of a 2D stress matrix in one clean expression. - Boolean Masking: Find every unsafe stress gauge
(
sigma > sigma_y) or cavitating pump point (NPSH_a < NPSH_r) cleanly usingarr[mask].
Core Array Creation, Slicing & Boolean Masks
| Function / Syntax | What It Builds | Mechanical Engineering Use |
|---|---|---|
np.array([1.0, 2.0]) |
Converts list/tuple to array | Force/displacement vectors |
np.linspace(a, b, N) |
N evenly spaced points
(b included!) |
Beam coordinates \(x \in [0, L]\) |
np.arange(a, b, step) |
Points spaced by step
(b excluded) |
Time steps \(0, 0.01, 0.02, \dots\) |
np.zeros((m, n)) /
np.ones |
All-zero / all-one 2D matrix | Stiffness matrices \(\mathbf{K}\), 2D grids |
arr[arr > limit] |
Boolean indexing / masking | Filter failing bolts or overheating nodes |
Watch Out! NumPy Array Slicing Creates a View, Not a Copy!
If you write sub = arr[2:5] and set
sub[:] = 0.0, arr itself
changes! That memory-saving design is intentional for huge
CFD/FEA arrays—whenever you want an independent slice, append
.copy() (sub = arr[2:5].copy()).
import numpy as np
from pathlib import Path
# Example 1 (Fluid Mechanics Real CSV Array Analysis): Pump NPSH & Operating Envelope Screening
pump_path = next(
p for p in [
Path("datasets/Fluids_Pump_and_Pipe_Network_Data.csv"),
Path("../datasets/Fluids_Pump_and_Pipe_Network_Data.csv"),
] if p.exists()
)
# Load numeric columns cleanly (skipping header row 0 and last string column via usecols)
data = np.loadtxt(pump_path, delimiter=",", skiprows=1, usecols=range(9))
Q_ls = data[:, 0] # Flow rate [L/s]
H_sys = data[:, 3] # System head [m]
H_pump = data[:, 4] # Pump head [m]
eta = data[:, 5] # Efficiency [-]
NPSHa = data[:, 7] # Available NPSH [m]
NPSHr = data[:, 8] # Required NPSH [m]
# Vectorized screening — ZERO for-loops!
npsh_margin = NPSHa - NPSHr
cavitating_Q = Q_ls[npsh_margin < 0.0]
head_diff = H_pump - H_sys
op_idx = np.argmin(np.abs(head_diff))
print("=== Vectorized Pump-Network Screening ===")
print(f"Tested Q range : {Q_ls.min():.1f} to {Q_ls.max():.1f} L/s ({len(Q_ls)} points)")
print(f"Operating point ~ : Q = {Q_ls[op_idx]:.1f} L/s (H_pump={H_pump[op_idx]:.2f} m, H_sys={H_sys[op_idx]:.2f} m, eta={eta[op_idx]*100:.1f}%)")
print(f"Cavitation danger Q : {cavitating_Q} L/s (NPSHa < NPSHr)")=== Vectorized Pump-Network Screening ===
Tested Q range : 20.0 to 150.0 L/s (10 points)
Operating point ~ : Q = 60.0 L/s (H_pump=45.34 m, H_sys=37.46 m, eta=67.7%)
Cavitation danger Q : [100. 110. 120. 130. 140. 150.] L/s (NPSHa < NPSHr)
# Example 2 (Solids + Sensor Data): PT100 Calibration & Yield Margin Vectorization
rtd_path = next(
p for p in [
Path("datasets/Solids_Tensile_Stress_Strain_RTD_Data.csv"),
Path("../datasets/Solids_Tensile_Stress_Strain_RTD_Data.csv"),
] if p.exists()
)
arr = np.loadtxt(rtd_path, delimiter=",", skiprows=1)
strain, sig_steel, sig_al, T_rtd, R_pt100 = arr.T # Unpack columns directly via transpose!
# Vectorized comparison against Al 6061 yield plateau (275 MPa)
safe_mask = sig_al < 275.0
max_elastic_strain = strain[safe_mask].max()
# Linear RTD approximation R ~ 100*(1 + 0.00385*T) vs exact Callendar-Van Dusen dataset
R_linear = 100.0 * (1.0 + 0.00385 * T_rtd)
max_lin_err_ohm = np.max(np.abs(R_linear - R_pt100))
print(f"Steel Peak Stress : {sig_steel.max():.2f} MPa | Al Peak Stress: {sig_al.max():.2f} MPa")
print(f"Al Max Strictly-Elastic Strain in Dataset: {max_elastic_strain*1e6:.0f} ueps")
print(f"PT100 Linear Approximation Max Deviation : {max_lin_err_ohm:.2f} Ohm (~{max_lin_err_ohm/0.385:.1f} degC)")Steel Peak Stress : 250.00 MPa | Al Peak Stress: 138.00 MPa
Al Max Strictly-Elastic Strain in Dataset: 2000 ueps
PT100 Linear Approximation Max Deviation : 11.01 Ohm (~28.6 degC)
Practice Questions (Concept Check)
- What happens when you execute
[1, 2, 3] * 2on a Pythonlistvs.np.array([1, 2, 3]) * 2on a NumPy array? - Why does
np.linspace(0.0, 2.0, 5)have5numbers (0.0, 0.5, 1.0, 1.5, 2.0) whilenp.arange(0.0, 2.0, 0.5)only has4? - What is Boolean masking, and how does
T[T > 600]work without anifstatement? - When slicing
row_view = M[0, :], why should you append.copy()if you plan to modifyrow_view?
Guided
Practice Problem 1 (Worked Self-Check): Moody Friction Error Statistics
(Fluids)
Load numeric columns of
datasets/Fluids_Moody_Friction_Dataset.csv using
np.loadtxt. Extract exact
f_EpsD_0p0005_Colebrook (col 3) and explicit
f_EpsD_0p0005_Haaland (col 4), compute the
vectorized percent relative error across all Reynolds
numbers, and print both the max error % and
mean turbulent error % (for \(Re_D \ge 4000\)).
Hint: Use mask = Re >= 4000 before computing .max() and .mean()
Remember in laminar flow (\(Re \le
2000\)), both columns equal \(64/Re\) (0% error), so
filtering Re >= 4000 measures true turbulent formula
accuracy!
# Worked Practice Problem 1 Solution: Vectorized Moody Error Screening
moody_path = next(
p for p in [
Path("datasets/Fluids_Moody_Friction_Dataset.csv"),
Path("../datasets/Fluids_Moody_Friction_Dataset.csv"),
] if p.exists()
)
m_arr = np.loadtxt(moody_path, delimiter=",", skiprows=1)
Re_arr = m_arr[:, 0]
f_cole = m_arr[:, 3]
f_haal = m_arr[:, 4]
pct_err = 100.0 * np.abs(f_haal - f_cole) / f_cole
turb_mask = Re_arr >= 4000
print(f"Max Turbulent Haaland Error : {pct_err[turb_mask].max():.3f}% at Re = {Re_arr[turb_mask][np.argmax(pct_err[turb_mask])]:.0e}")
print(f"Mean Turbulent Haaland Error : {pct_err[turb_mask].mean():.3f}%")Max Turbulent Haaland Error : 1.279% at Re = 1e+05
Mean Turbulent Haaland Error : 0.644%
End-of-Chapter Practice Problems (Try Yourself!)
- Vectorized Axial Bar Stress & Safety Factor
(
Statics / Solids): Generate 12 rod diameters withnp.linspace(12.0, 34.0, 12)[mm] carrying axial loadF = 48_000N. Compute cross-sectional areas, stresses in MPa, and safety factors against \(S_y = 250\text{ MPa}\), returning ONLY diameters that satisfy \(\text{FOS} \ge 2.2\). - Pin-Fin Heat Sink Efficiency Matrix
(
Heat Transfer): Loaddatasets/HMT_Pin_Fin_Heat_Sink_Data.csv, compute thermal power dissipated per unit conductanceQ / (1/R_th)check and verify average overall surface efficiency (col 6). - 2D Broadcasting Temperature Grid
(
Thermodynamics / Conduction): Create a \(5 \times 6\) temperature grid (\(T(x, y)\)) usingnp.meshgridover \(x \in [0, 0.4]\text{ m}, y \in [0, 0.3]\text{ m}\) where \(T = 300 + 120\sin(\pi x / 0.4)\sinh(\pi y / 0.4)\), and print the center and max plate temperatures.