[Python-ideas] Float range class

Andrew Barnert abarnert at yahoo.com
Fri Jan 9 23:17:20 CET 2015


On Jan 9, 2015, at 13:22, Ethan Furman <ethan at stoneleaf.us> wrote:

> On 01/09/2015 12:58 PM, Andrew Barnert wrote:
> 
>> arange is actually very easy to get right, but hard to _use_ properly. A half-open range of values from 0 to .9 by .3
>> is going to include a number just under 0.9 if properly implemented. However you slice it, .3*3<.9, .3+.3+.3<.9, etc.,
>> so that number belongs in the range.
> 
> As a non-maths person (no degree, passingly familiar with algebra, light trigonometry, what little I remember from
> calculus) can you explain that to me?  Why does a number slightly less than .9 /have/ to be in the results for a
> "properly implemented" frange?
> 
>  def frange(start, stop, step):
>      count, remainder = divmod(stop - start, step)
>      count = int(count)
>      if remainder > 0.00000001:
>           count += 1
>      for i in range(count):
>          yield start + i * step

Try it with step=1e-12. 

This is equivalent on designing float.__eq__ as something like abs(self-other) < 0.00000001. At first glance it seems like that makes all floating point comparison problems go away, until you try it with small floats and suddenly 9e-12 - 1e-12 == 4e-12.

The right epsilon to use depends on the specific problem space, so it can't be hardcoded into a general-purpose function.


More information about the Python-ideas mailing list