range for floats
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python's built-in range() only works with integers. To generate a sequence of floating-point numbers, use numpy.arange() for NumPy-based workflows, numpy.linspace() for evenly spaced points between endpoints, or a custom generator function. The most reliable approach is numpy.linspace() because it avoids the floating-point accumulation errors that affect step-based methods.
Why range() Does Not Support Floats
Python's range() is strictly integer-based because floating-point arithmetic introduces rounding errors that make it impossible to guarantee the exact number of elements in the sequence.
Method 1: numpy.arange()
numpy.arange follows the same start/stop/step convention as range. The stop value is exclusive, but floating-point rounding can produce unexpected results near the boundary.
Method 2: numpy.linspace() (Recommended)
linspace is preferred over arange because you specify the number of points instead of the step size. This guarantees the exact number of elements and always includes the endpoint (unless endpoint=False).
Method 3: Custom Generator (No NumPy)
A custom generator avoids the NumPy dependency but requires careful rounding to prevent floating-point drift.
Method 4: Multiplication-Based (Most Accurate Without NumPy)
Computing each value as start + i * step avoids the accumulation error that occurs when repeatedly adding step to a running total.
Method 5: Using decimal for Exact Arithmetic
Decimal provides exact decimal arithmetic, eliminating the floating-point rounding issues that plague float-based approaches.
Floating-Point Accumulation Error
0.1 cannot be represented exactly in binary floating-point. Each addition introduces a tiny error, and these errors accumulate over many iterations.
Comparison Table
| Method | Requires NumPy | Endpoint Control | Accuracy | Memory |
numpy.arange | Yes | Exclusive (unreliable at boundary) | Good | Array |
numpy.linspace | Yes | Inclusive/exclusive | Best | Array |
| Custom generator | No | Exclusive | Needs rounding | Lazy |
| Multiplication-based | No | Exclusive | Very good | Lazy |
Decimal-based | No | Exclusive | Exact | Lazy |
Common Pitfalls
- Assuming
numpy.arangeincludes or excludes the endpoint predictably: Due to floating-point rounding,np.arange(0, 1.0, 0.1)may produce 10 or 11 elements depending on the platform. Uselinspacefor deterministic element counts. - Accumulating step values with
+=: Repeatedly adding0.1to a float causes drift. After 10 additions, the result is0.9999999...instead of1.0. Use multiplication (start + i * step) orDecimalfor accuracy. - Using
range()with float arguments:range()raisesTypeErrorfor float arguments. This is by design — there is no way to guarantee integer-like behavior with floats. - Not specifying
numcorrectly inlinspace:np.linspace(0, 1, 10)produces 10 points with endpoint 1.0 included. If you expect steps of 0.1, you neednum=11(10 intervals = 11 points). Off-by-one errors are common. - Using a float range for equality comparisons: Comparing floats with
==after generating them via a range is unreliable. Usemath.isclose()or a tolerance check:abs(a - b) < 1e-9.
Summary
- Python's
range()only supports integers — usenumpy.arange()ornumpy.linspace()for float sequences numpy.linspace(start, stop, num)is the most reliable because you specify the number of points, not the step size- For no-NumPy solutions, use multiplication-based generation (
start + i * step) to avoid float accumulation errors - Use
Decimalfor exact decimal arithmetic when precision is critical - Never compare float range values with
==— usemath.isclose()or tolerance-based comparisons numpy.arangeendpoint inclusion is unpredictable — preferlinspacefor deterministic results
Related reading
- Rank items in an array using Python/NumPy, without sorting array twice
- Read a file line by line from S3 using boto?
- Read file content from S3 bucket with boto3
- Read in Large CSV File and feed into TensorFlow
- Read .mat files in Python
- Read only mode in keras
- Read only the first line of a file?
- Read specific columns from a csv file with csv module?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.