[Python-ideas] Float range class

Ethan Furman ethan at stoneleaf.us
Fri Jan 9 22:22:42 CET 2015


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

  list(frange(0.3, 0.9, 0.3))
  [0.3, 0.6]

  list(frange(0.3, 1, 0.3))
  [0.3, 0.6, 0.89999999999999]

--
~Ethan~

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150109/1600d778/attachment.sig>


More information about the Python-ideas mailing list