Use numpy.linspace(start, stop, num) when you know the exact number of points you want (eliminating floating-point drift at endpoints), numpy.arange(start, stop, step) when you need a step-driven NumPy array, or a pure-Python integer-scaled generator ((start + i * step for i in range(n)) or decimal.Decimal) when you want zero third-party dependencies without binary floating-point rounding drift.
Basic Example
import numpy as np
from decimal import Decimal
# 1. Recommended (NumPy — fixed endpoint count, zero endpoint drift):
# Generate 5 evenly spaced values from 0.0 to 1.0 inclusive:
print(np.linspace(0.0, 1.0, 5))
# Output: [0. 0.25 0.5 0.75 1. ]
# 2. NumPy step-based sequence (half-open [start, stop) like range()):
print(np.arange(0.0, 1.0, 0.2))
# Output: [0. 0.2 0.4 0.6 0.8]
# 3. Pure Python (no third-party libraries, exact decimal steps):
def decimal_range(start: str, stop: str, step: str):
curr, end, inc = Decimal(start), Decimal(stop), Decimal(step)
while curr < end:
yield curr
curr += inc
print([float(x) for x in decimal_range("0.0", "1.0", "0.2")])
# Output: [0.0, 0.2, 0.4, 0.6, 0.8]
Key Details & Edge Cases
- Why Python’s built-in
range()rejects floats (TypeError: 'float' object cannot be interpreted as an integer):range()requires exact integers because binary IEEE 754 floats cannot represent most base-10 fractions exactly (0.1 + 0.1 + 0.1 == 0.30000000000000004), making stop-boundary inclusion unpredictable.
- Avoid repeated
x += stepfloat accumulation in pure Python—useround(start + i * step, ndigits):- Repeatedly adding
0.1accumulates rounding error on every step. Instead, compute each element directly from integer indexi:steps = [round(0.0 + i * 0.1, 10) for i in range(10)] # Output: [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
- Repeatedly adding
- Watch out for
np.arange()endpoint instability whenstop - startis an exact multiple ofstep:- Because of floating-point precision,
np.arange(0.0, 0.3, 0.1)returns 3 items ([0.0, 0.1, 0.2]), whereasnp.arange(0.0, 0.6, 0.1)can occasionally include0.6(7items instead of6)! Always prefernp.linspace(start, stop, num)whenever the exact element count matters.
- Because of floating-point precision,
- Passing string literals to
Decimal("0.1")instead of floatsDecimal(0.1):- Calling
Decimal(0.1)converts the already-imprecise binary float (Decimal('0.1000000000000000055511151231257827021181583404541015625')). Always pass strings (Decimal("0.1")) when exact financial or decimal arithmetic is required.
- Calling
- Negative step sizes (counting downward):
- Both
np.linspace(1.0, 0.0, 6)andnp.arange(1.0, 0.0, -0.2)support descending sequences; fordecimal_range, checkcurr > endwheninc < 0.
- Both
Comparison of Decimal / Floating-Point Sequence Generators in Python
| Method | Dependency | Endpoint Precision | Output Type | Best Used When |
|---|---|---|---|---|
np.linspace(start, stop, num) (Recommended) |
numpy |
Exact (stop included by default; endpoint=False optional) |
np.ndarray |
Scientific computing, plotting axes, simulations, and whenever an exact sample count is needed. |
np.arange(start, stop, step) |
numpy |
Subject to float rounding near stop |
np.ndarray |
Step-driven numeric arrays where approximate bounds are acceptable. |
[round(start + i * step, n) for i in range(k)] |
Built-in range |
Cleanly rounded (no cumulative drift) | list[float] |
Lightweight pure-Python scripts needing float lists without installing NumPy. |
Decimal generator (curr += Decimal(step)) |
Built-in decimal |
100% exact base-10 | Iterator[Decimal] |
Financial pricing tiers, currency increments, and exact decimal tolerances. |
You must log in or register to comment.
