pythonnumpy

Why does np.linspace(1,5,5, dtype = int, endpoint=False) result in an array that contains 1 twice?


While looking to replicate:

In [61]: np.arange(0,5)
Out[61]: array([0, 1, 2, 3, 4])

using np.linspace(), I observed:

In [70]: np.linspace(1,5,5, dtype = int, endpoint=False)
Out[70]: array([1, 1, 2, 3, 4])

Why does np.linspace() include the value 1 twice in this case?


Solution

  • because linspace is defined on floats and returns in your case:

    np.linspace(1,5,5, endpoint=False)
    array([ 1. ,  1.8,  2.6,  3.4,  4.2])
    

    then using int as dtype just rounds down giving you the result with two 1:

    array([ 1 ,  1,  2,  3,  4])
    

    Btw: Using np.arange might be better suited if you want to create arrays containing integer:

    np.arange(1,5)
    array([ 1,  2,  3,  4])