[Python-ideas] Float range class

M.-A. Lemburg mal at egenix.com
Fri Jan 9 11:55:04 CET 2015


On 08.01.2015 18:12, Todd wrote:
> On Thu, Jan 8, 2015 at 5:18 PM, M.-A. Lemburg <mal at egenix.com> wrote:
>> I think you'd first have to describe some use cases, since it's
>> not at all clear what you mean with "float range", e.g. you
>> could be referring to:
>>
>> * interval arithmetics: http://en.wikipedia.org/wiki/Interval_arithmetic
>>
>> * ranges of numbers with a fixed stepping (which can create problems
>>   near the edges due to rounding issues)
>>
> 
> 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

It's a generator. If you need a list, wrap it into list(frange(...)).

The calculation may look a little awkward. That's on purpose to
reduce fp rounding errors.

tmp/frange> python3.4 -i frange.py
>>> list(frange(0,1,3))
[0.0, 0.3333333333333333, 0.6666666666666666, 1.0]
>>> list(frange(0,1,4))
[0.0, 0.25, 0.5, 0.75, 1.0]
>>> list(frange(0,1,5))
[0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
>>> list(frange(0,1,6))
[0.0, 0.16666666666666666, 0.3333333333333333, 0.5, 0.6666666666666666, 0.8333333333333334, 1.0]
>>>

Both sides of the range are included. If you need one side open, simply
leave out the first or last element of the list.

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