python numpy arange unexpected results

I’m guessing that you’re seeing the effects of floating point rounding.

numpy.arange does the same thing as python’s range: It doesn’t include the “endpoint”. (e.g. range(0, 4, 2) will yield [0,2] instead of [0,2,4])

However, for floating point steps, the rounding errors are accumulate, and occasionally the last value will actually include the endpoint.

As noted in the documentation for arange:

When using a non-integer step, such as 0.1, the results will often not
be consistent. It is better to use linspace for these cases.

numpy.linspace generates a specified number of points between a starting and ending point. Incidentally, it does include the endpoints by default.

Leave a Comment