I am using the arange function to define my for loop iterations and getting unexpected results.
i = arange(7.8,8.4,0.05)
print i
yeilds the following:
[ 7.8 7.85 7.9 7.95 8. 8.05 8.1 8.15 8.2 8.25 8.3 8.35 8.4 ]
yet using the stop value of 8.35 as follows
i = arange(7.8,8.35,0.05)
yields the following
[ 7.8 7.85 7.9 7.95 8. 8.05 8.1 8.15 8.2 8.25 8.3 ]
But I want my range to end at 8.35! I know I can use the stop value of > 8.35 and < 8.4 to achieve my result, but why is it different and in my mind, inconsistent?
Edit: I am using version 2.7
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With