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? ;)
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 .
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.
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.
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. ])
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