On 8/26/2020 6:40 AM, dn via Python-list wrote:
def fp_range( start:float, stop:float, step:float=1.0 )->float:
     """Generate a range of floating-point numbers."""
     if stop <= start:
         raise OverflowError( "RangeError: start must be less than stop" )
     x = start
     while x < stop:
         yield x
         x += step

This only works exactly as expected for fraction steps of k/2**n give exactly. Your only tests used .5 and .25.

print(list(fp_range(0.0, 2.01, .1)))
produces
[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999, 0.9999999999999999, 1.0999999999999999, 1.2, 1.3, 1.4000000000000001, 1.5000000000000002, 1.6000000000000003, 1.7000000000000004, 1.8000000000000005, 1.9000000000000006, 2.0000000000000004]

For exact fractional steps, one should use fractions or multiply and divide by the denominator, as shown by Joel, after stepping by the numerator.


--
Terry Jan Reedy


--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to