Result Of Function Linspace

29 September 2019 - 1 answer

Could you explain me this result please? I expected value as `[0, 0.1, 0.4, 0.9, ...]`.

``````>>> np.linspace(0, 1, 10) ** 2
array([0.        , 0.01234568, 0.04938272, 0.11111111, 0.19753086,
0.30864198, 0.44444444, 0.60493827, 0.79012346, 1.        ])
``````

`np.linspace(0, 1, 10)` gives ten values including both endpoints:

``````>>> np.linspace(0, 1, 10)
array([0.        , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
0.55555556, 0.66666667, 0.77777778, 0.88888889, 1.      ])
``````

When you square these values, you get the numbers you see. This is referred to as a "fence-post problem"; 10 posts give you only 9 panels:

``````1 2 3 4 5 6 7 8 9 10
|-|-|-|-|-|-|-|-|-|
1 2 3 4 5 6 7 8 9
``````

so each step is actually 1/9, not 1/10. I think you wanted:

``````>>> np.linspace(0, 1, 11) ** 2
array([0.  , 0.01, 0.04, 0.09, 0.16, 0.25, 0.36, 0.49, 0.64, 0.81, 1.  ])
``````

Alternatively, if you don't want `1.` at the end, you can explicitly exclude the endpoint per the docs:

``````>>> np.linspace(0, 1, 10, endpoint=False) ** 2
array([0.  , 0.01, 0.04, 0.09, 0.16, 0.25, 0.36, 0.49, 0.64, 0.81])
``````