Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range with step of type float [duplicate]

Tags:

python

range

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) { /* ... */ }
like image 496
Albert Avatar asked Nov 15 '10 23:11

Albert


People also ask

Can we use float value in step in range ()?

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 .

What is the range for float type?

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.

How do you use the range of a float function?

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.


3 Answers

You could use numpy.arange.

EDIT: The docs prefer numpy.linspace. Thanks @Droogans for noticing =)

like image 181
Katriel Avatar answered Oct 08 '22 07:10

Katriel


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
like image 36
Zarkonnen Avatar answered Oct 08 '22 08:10

Zarkonnen


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)]

like image 13
mariana soffer Avatar answered Oct 08 '22 06:10

mariana soffer