0

I am writing a doctest for my utility function to generate a sequence of floating point numbers. However I am unable to match some of the intermediate values that are getting generated. Not sure why some values are long decimal.

def frange(initial, final, increment):
    """ Return the list of numbers in float format.

    >>> frange(0, 0.7, 0.1)
    [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]

    """
    lst = []
    while(final > initial):
        lst.append(initial)
        initial += increment

    return lst

File "foo.py", line 4, in __main__.frange
Failed example:
    frange(0, 0.7, 0.1)
Expected:
    [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
Got:
    [0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6]
**********************************************************************
1 items had failures:
   1 of   1 in __main__.frange
***Test Failed*** 1 failures.
frankegoesdown
  • 1,898
  • 1
  • 20
  • 38
Sanjeev Singh
  • 141
  • 1
  • 10
  • Seems to be a rounding issue – Carsten Jul 26 '19 at 12:04
  • That's a general problem with computer's format of addition, especially floating point precision in IEEE 753 format. More on that here : https://www.youtube.com/watch?v=PZRI1IfStY0 and https://docs.python.org/3/tutorial/floatingpoint.html – LazyCoder Jul 26 '19 at 12:07

0 Answers0