Home > other >  numpy arange step iteration error logging for dtype=int vs float
numpy arange step iteration error logging for dtype=int vs float

Time:03-25

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]

CodePudding user response:

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.

CodePudding user response:

Answer to my question is as what hpaulj mentioned, in correct use of arange could lead to unexpected behavior. decimal point for int is bad practise and therefore resulted in the behavior.

  • Related