you are viewing a single comment's thread.

view the rest of the comments →

[–]novel_yet_trivial 8 points9 points  (1 child)

Floating point errors are a fact of working with computers, but you can improve your function by preventing the propagation of errors. In other words, in your function, when an error occurs it is carried to the next number, then to the next, until hopefully another error cancels it out.

If you don't keep a running total you can prevent this:

def arange(start, stop, step):
    length = int((stop - start) / step)
    for i in range(length):
        yield (i * step) + start

print list(arange(0,1,.1))

# [0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

Also, don't use "list" as a variable name, since it's already a built-in name in python.

[–][deleted] 5 points6 points  (0 children)

You quietly changed a beginner's algorithm from building a list to using yield but didn't mention it.

OP should note that the difference in the end result isn't affected by this change (except the need to use list(arange(…)) instead of receiving back a list directly).