[Python-ideas] Float range class
M.-A. Lemburg
mal at egenix.com
Fri Jan 9 12:28:13 CET 2015
On 09.01.2015 12:01, Chris Angelico wrote:
> On Fri, Jan 9, 2015 at 9:55 PM, M.-A. Lemburg <mal at egenix.com> wrote:
>>> This is what I am talking about. The idea would be to have something that
>>> is, as much as possible, identical to the existing range. I understand it
>>> has floating-point issues, but any other approach would as well.
>>
>> This should do the trick:
>>
>> def frange(start, stop, steps):
>> start = float(start)
>> stop = float(stop)
>> steps = int(steps)
>> for i in range(steps + 1):
>> yield ((steps - i) * start + i * stop) / steps
>
> Thing is, a range object is a lot more than just an iterable. In many
> ways, it acts just like list(self) would - you can index it, slice it,
> etc:
>
>>>> r = range(10, 101, 10)
>>>> list(r)
> [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>>> r.index(70)
> 6
>>>> r[6]
> 70
>>>> len(r)
> 10
>>>> r[1:-4:2]
> range(20, 70, 20)
>
> Does frange() need to be able to do all these operations?
Probably 95% of all uses of range() in my own code never use range
object features beyond that of being iterable. For everything
else you can create either a list or throw itertools at it :-)
IMO, the only reason for having an frange() function in (probably)
the math module is to provide an implementation which tries to
reduce fp rounding problems to a minimum.
Other than that, it's just too simple to add straight to the
application code in a way which exactly fits the purpose and
functionality needed by that application. For decimals and
date/time values, the naive algorithm is good enough, so the
above argument doesn't apply to those.
--
Marc-Andre Lemburg
eGenix.com
Professional Python Services directly from the Source (#1, Jan 09 2015)
>>> Python Projects, Coaching and Consulting ... http://www.egenix.com/
>>> mxODBC Plone/Zope Database Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/
________________________________________________________________________
::::: Try our mxODBC.Connect Python Database Interface for free ! ::::::
eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
Registered at Amtsgericht Duesseldorf: HRB 46611
http://www.egenix.com/company/contact/
More information about the Python-ideas
mailing list