[Python-ideas] Float range class

Todd toddrjen at gmail.com
Thu Jan 8 18:22:27 CET 2015


On Thu, Jan 8, 2015 at 5:31 PM, Chris Barker <chris.barker at noaa.gov> wrote:

> it does  this in the naive way: starting with start, continuing to add
> step, until the value is >= stop, at which point it terminates without
> including that last value. This is fine and dandy for integers, but is a
> mess with floats, due to rounding and binary storage under the hood (i.e
> floats can not precisely represent common base-10 steps). This is
> particularly a problem when you ant a particular end point to be included,
> you then need to increase stop to a bit more than you want, so as to make
> sure it gets included, but then you can accidentally get one too many.
>

I would think that a floating range class would necessarily use
multiplication rather than repeated addition (to allow indexing at
arbitrary point), which would avoid cumulative floating-point errors
(although it would still have a smaller floating point error at the end),
and for the same reason the final value would have to be pre-computed
rather than using a naive ">=" which would allow it to be a bit smarter.


> This is almost never what people really want, though it does work as
> expected most of the time -- that most of the time is the catch -- future
> bugs lurking.
>
> So: the accepted practice in numpy (and often espoused to newbies on the
> mailing list) is to not use arange() for floats. Instead, the "linspace()"
> function is recommended. This function returns evenly spaced numbers over a
> specified interval, guaranteeing that you get the start an end points you
> want included. It has optional arguments that let you define the spacing in
> various ways, but the key is that the algorithms are designed to give the
> user what is expected,  regardless of floating point nuance.
>
>
If there was a range module (rangetools?), it could also contain a
count-based floating point class.  But, at least in my own experience, I
use arange when I want an interval-based range, and linspace when I want a
count-based range.  It just depends on what, exactly, I am trying to do.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150108/01dae22c/attachment.html>


More information about the Python-ideas mailing list