The best way to get what you want is to use linspace. To get a vector x
that is almost the same as in your example, you should do
x = np.linspace(-np.pi/4, np.pi/4, round(np.pi / 2 / 0.001) + 1)
or simply
x = np.linspace(-np.pi/4, np.pi/4, npoints)
This gives you exactly npoints
points, and the start and stop values are guaranteed to be included.
Using np.arange(start, stop, step)
gives you the points start, start+step, start+2*step, ...
until the final point for which start+n*step < stop
. Due to floating point inaccuracies, it is not obvious what is the n
of the final point. The manual of arange
remarks:
When using a non-integer step, such as 0.1, the results will often not
be consistent. It is better to use linspace for these cases.
It is easy to demonstrate that this leads to unpredictable behavior by generating some aranges between 0 and 1 with variable step size:
In [21]: for i in range(97,109):
...: r = np.arange(0, 1, 1. / i)
...: print 'step = 1.0 / {}, length = {}, last value = {}'.format(
...: i, len(r), r[-1])
...:
step = 1.0 / 97, length = 97, last value = 0.989690721649
step = 1.0 / 98, length = 99, last value = 1.0
step = 1.0 / 99, length = 99, last value = 0.989898989899
step = 1.0 / 100, length = 100, last value = 0.99
step = 1.0 / 101, length = 101, last value = 0.990099009901
step = 1.0 / 102, length = 102, last value = 0.990196078431
step = 1.0 / 103, length = 104, last value = 1.0
step = 1.0 / 104, length = 104, last value = 0.990384615385
step = 1.0 / 105, length = 105, last value = 0.990476190476
step = 1.0 / 106, length = 106, last value = 0.990566037736
step = 1.0 / 107, length = 108, last value = 1.0
step = 1.0 / 108, length = 108, last value = 0.990740740741
See also this answer to a related question.