Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

range() with float step argument [duplicate]

Tags:

python

Possible Duplicate:
Python decimal range() step value

I would like generate list like this:

[0, 0.05, 0.1, 0.15 ... ]

range(0, 1, 0.05) would be great but it doesn't work beacuse:

range() integer step argument expected, got float.

Have you any elegant idea? ;)

like image 298
David Silva Avatar asked Sep 13 '12 09:09

David Silva


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 .

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.

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.


1 Answers

If you can use numpy, it's a good idea to use numpy.linspace. Functions that try to fit range logic on floating-point numbers, including numpy's own arange, usually get confusing regarding whether the end boundary ends up in the list or not. linspace elegantly resolves that by having you to explicitly specify the start point, the end point, and the desired number of elements:

>>> import numpy
>>> numpy.linspace(0.0, 1.0, 21)
array([ 0.  ,  0.05,  0.1 ,  0.15,  0.2 ,  0.25,  0.3 ,  0.35,  0.4 ,
        0.45,  0.5 ,  0.55,  0.6 ,  0.65,  0.7 ,  0.75,  0.8 ,  0.85,
        0.9 ,  0.95,  1.  ])
like image 71
user4815162342 Avatar answered Sep 28 '22 18:09

user4815162342