Reputation: 629
For reasons that I cannot understand, Python3 still doesn't supply a built-in range()
like generator object for floats.
So enter numpy.arange()
. However that function returns an array. Arrays of floats simply for iteration make no fundamental sense when they are very large, which for my uses are common.
Is there a function within numpy that supplies a generator version of arange()
, or am I left to code it by hand?
Upvotes: 0
Views: 1018
Reputation: 231605
The lack of float support in range
doesn't seem like a big fault. The suggested link shows all kinds of ways of generating the numbers. They also point out the tricky issues. numeric_range
also discusses these issues.
arange
can handle float steps, but with a warning.
In [79]: np.arange(0,10,1.25)
Out[79]: array([0. , 1.25, 2.5 , 3.75, 5. , 6.25, 7.5 , 8.75])
linspace
is recommended instead, with better end point control. For what it's worth MATLAB also has a linspace
function.
In [80]: np.linspace(0,10,9)
Out[80]: array([ 0. , 1.25, 2.5 , 3.75, 5. , 6.25, 7.5 , 8.75, 10. ])
But my gut feeling is that scaling range
output would be the cleanest generator:
In [81]: g = (i*1.25 for i in range(9)) # generator expression
In [82]: list(g)
Out[82]: [0.0, 1.25, 2.5, 3.75, 5.0, 6.25, 7.5, 8.75, 10.0]
One of the link answers suggests itertools.takewhile
:
In [83]: import itertools
In [86]: g = itertools.takewhile(lambda x: x<10, itertools.count(0,1.25))
In [87]: list(g)
Out[87]: [0, 1.25, 2.5, 3.75, 5.0, 6.25, 7.5, 8.75]
Both of these answers feed one generator to another, consistent with the philosophy I cited in my comment. Building complex actions by stringing together smaller building blocks is typical Python, and even more so numpy
.
Upvotes: 1