The documentation basically says that range
must behave exactly as this implementation (for positive step
):
def range(start, stop, step):
x = start
while True:
if x >= stop: return
yield x
x += step
It also says that its arguments must be integers. Why is that? Isn't that definition also perfectly valid if step is a float?
In my case, I am esp. needing a range
function which accepts a float type as its step
argument. Is there any in Python or do I need to implement my own?
More specific: How would I translate this C code directly to Python in a nice way (i.e. not just doing it via a while
-loop manually):
for(float x = 0; x < 10; x += 0.5f) { /* ... */ }
The Python range() works only with integers. It doesn't support the float type, i.e., we cannot use floating-point/decimal value in any of its arguments. For example, If you use range() with float step argument, you will get a TypeError 'float' object cannot be interpreted as an integer .
Since the high-order bit of the mantissa is always 1, it is not stored in the number. This representation gives a range of approximately 3.4E-38 to 3.4E+38 for type float.
NumPy linspace function to generate float range It has the following syntax: # Syntax linspace(start, stop, num, endpoint) start => starting point of the range stop => ending point num => Number of values to generate, non-negative, default value is 50. endpoint => Default value is True.
You could use numpy.arange
.
EDIT: The docs prefer numpy.linspace
. Thanks @Droogans for noticing =)
One explanation might be floating point rounding issues. For example, if you could call
range(0, 0.4, 0.1)
you might expect an output of
[0, 0.1, 0.2, 0.3]
but you in fact get something like
[0, 0.1, 0.2000000001, 0.3000000001]
due to rounding issues. And since range is often used to generate indices of some sort, it's integers only.
Still, if you want a range generator for floats, you can just roll your own.
def xfrange(start, stop, step):
i = 0
while start + i * step < stop:
yield start + i * step
i += 1
In order to be able to use decimal numbers in a range expression a cool way for doing it is the following: [x * 0.1 for x in range(0, 10)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With