Mathematical modeling, data plotting, and algorithm testing often require continuous sequences of evenly distributed numbers. NumPy provides three core sequence generation engines: np.arange(), np.linspace(), and np.logspace().
1. Step-Based Sequences with np.arange()
np.arange() is the NumPy counterpart to Python's built-in range(), but returns a contiguous ndarray and supports floating-point steps:
7print(a)# [0 1 2 3 4 5 6 7 8 9] (Stop value 10 is EXCLUDED!)
8
9# 10 to 50 with step of 5
10b = np.arange(10,50,5)
11print(b)# [10 15 20 25 30 35 40 45]
12
13# Floating point step
14c = np.arange(0.0,1.0,0.2)
15print(c)# [0. 0.2 0.4 0.6 0.8]
The Floating-Point Step Hazard in arange:
Because computer hardware stores floating-point numbers in binary fractions, steps like 0.1 have minor precision rounding errors. Sometimes np.arange(0, 0.3, 0.1) returns 3 elements, and sometimes 4 depending on floating-point round-off!
For floating-point sequences, ALWAYS use np.linspace() instead!
Click to Zoom
Array Creation and Numerical Ranges
2. Sample-Count Sequences with np.linspace()
When generating sample points for charting (such as generating 100 points between $0$ and $2pi$ to plot a smooth Sine wave), you do not know the step size; you know how many points you want. np.linspace() solves this perfectly:
3# Generate exactly 5 evenly spaced points between 0 and 1
4pts = np.linspace(0,1,5)
5print(pts)# [0. 0.25 0.5 0.75 1. ]
Key Properties of linspace:
Endpoint is Included: Unlike arange(), the stop value is included by default!
Calculating the Step: NumPy calculates the exact step internally: step = (stop - start) / (num - 1).
Retaining the Step Size: Pass retstep=True to get both the array and the calculated step delta:
1 arr, step = np.linspace(0,100,5, retstep=True)
2print(step)# 25.0
3. Logarithmic Scales with np.logspace()
For frequencies, decibels, seismic Richter scales, or machine learning hyperparameter tuning (e.g., testing learning rates across orders of magnitude from $10^{-4}$ to $10^{1}$):