function with variable arguments

Harald Schmidt hsml at lycos.de
Sat May 14 09:59:05 EDT 2005


Xah Lee wrote:

> I think it would be a improvement for the built-in range() so that step
> needs not be an integer. [...]
>
> Range( 5, 7, 0.3); # returns [5, 5.3, 5.6, 5.9, 6.2, 6.5, 6.8]

This may not return what you expect it to return.

For example let's use a naive implementation like this:

def Range(start, stop, step):
  values = []
  while start < stop:
    values.append(start)
    start += step
  return values

The result is:
>>> Range(5, 7, 0.3)
[5, 5.2999999999999998, 5.5999999999999996, 5.8999999999999995,
6.1999999999999993, 6.4999999999999991, 6.7999999999999989]

Worse: Range(5, 7.1, 0.3) would return 8 values, not 7 as expected from e.g.
range(50, 71, 3).

Welcome to the interesting world of floating point numbers.

 Harald




More information about the Python-list mailing list