[SOLVED] numpy arange step iteration error logging for dtype=int vs float

Issue

I am new to numpy and have a look at the documentation https://numpy.org/devdocs/reference/generated/numpy.arange.html but cant seem to get an error log or an indication that it is exceeding the stop of int ‘3’. float seems to work as expected, but not int. i believe its due to how python interpret int and float, but should int not auto round the 0.5 values?
Comparing a float and an int in Python
https://numpy.org/doc/stable/user/basics.types.html

my question is, why and how does arange interpret the int as the stop point is ‘6’ and not ‘3’, if int is used, should it not stop at 2?

Many thanks for enlightenment.

x = np.arange(-1, 3, 0.5, dtype=int)
y = np.arange(-1, 3, 0.5, dtype=float)
print('x = ', x)
print('y = ', y)


x =  [-1  0  1  2  3  4  5  6]
y =  [-1.  -0.5  0.   0.5  1.   1.5  2.   2.5]

Solution

According to the docs, which you must have read, since your example is close to the one given there

Another stability issue is due to the internal implementation of
`numpy.arange`.
The actual step value used to populate the array is
``dtype(start + step) - dtype(start)`` and not `step`. Precision loss
can occur here, due to casting or due to using floating points when
`start` is much larger than `step`. This can lead to unexpected
behaviour.

That dtype(start + step) - dtype(start):

In [25]: int(-1 + .5) - int(-1)
Out[25]: 1

Looks like it initially calculates the number of values to return, using the same math as with the float case – hence x and y have the same length.

ceil((stop - start)/step)

In [29]: np.ceil((3-(-1))/.5)
Out[29]: 8.0

My guess is that it ‘iterates’ for [29] values with the [25] step. It’s not a ‘iterate until it reaches/passes the stop‘ logic.

Answered By – hpaulj

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *