[Python] Apparently weird condition on inclusion of endpoint in np.arange() [duplicate]

Discussão em 'Python' iniciado por Stack, Abril 16, 2025.

  1. Stack

    Stack Membro Participativo

    The numpy.arange function takes the three parameters: start, stop, step (positional args.) The default step is 1. Throughout my entire Numpy experience, the last element of the resultant array is not stop, it is (stop - step). And so if you run, for example, the following code, you'll get the following output:

    import numpy as np
    a = np.arange(0,1, 0.05)


    Output:

    array([0. , 0.05, 0.1 , 0.15, 0.2 , 0.25, 0.3 , 0.35, 0.4 , 0.45, 0.5 ,
    0.55, 0.6 , 0.65, 0.7 , 0.75, 0.8 , 0.85, 0.9 , 0.95])


    As you can see, the last element of a does not have 1 (stop)

    Now have a look at the following array:

    b1 = np.arange(0.9, 1, 0.05)


    Output:

    array([0.9 , 0.95])


    ... as expected.

    But, now:

    b2 = np.arange(0.9, 1.1, 0.05) # b2 only has stop different from b1


    Output:

    array([0.9 , 0.95, 1. , 1.05, 1.1 ])


    b2 includes the stop!

    There is much more to this quirk, and I was given a Geminin overview that mentioned floatiog point approximations. However, this off-by-one error left me scratching my head for almost an entire day, it killed my code, which was based on array addition and indexing, and so index out-of-range errors were being raised the entire time. (I had planned to ask my TAs questions related to data analysis, which I had planned to prepare using NumPy, but this thing creeped in and I couldn't!).

    The annoying thing is that this is not a special case, nor does it seem to have some pattern. So please explain what is going on.

    I am using Python 3.13.0 and NumPy version 2.2.1.

    Continue reading...

Compartilhe esta Página