# [Numpy-tickets] [NumPy] #264: linspace endpoint not always honored

NumPy numpy-tickets at scipy.net
Mon Aug 21 11:39:44 CDT 2006

```#264: linspace endpoint not always honored
-----------------------+----------------------------------------------------
Reporter:  baxissimo  |       Owner:  somebody
Type:  defect     |      Status:  new
Priority:  normal     |   Milestone:
Component:  numpy.lib  |     Version:
Severity:  normal     |    Keywords:
-----------------------+----------------------------------------------------
It is not always the case that
linspace(start,stop,num)[-1] == stop

The following little example should output [], but it doesn't.
{{{
In [390]: filter(lambda x: x[1]!=0.0, [ (i, 1.0-numpy.linspace(0,1,i)[-1])
for i in range(2,200) ])
Out[390]:
[(50, 1.1102230246251565e-016),
(99, 1.1102230246251565e-016),
(104, 1.1102230246251565e-016),
(108, 1.1102230246251565e-016),
(162, 1.1102230246251565e-016),
(188, 1.1102230246251565e-016),
(197, 1.1102230246251565e-016),
(198, 1.1102230246251565e-016)]
}}}

I know it's not a good idea to count on floating point equality in
general, but it doesn't seem too much to expect that the first and last
values returned by linspace are exactly the values asked for if they both
have exact floating point representations.

The simplest fix is to just add in a
{{{
y[-1] = stop
}}}
in the case of endpoint=True.  So the code would become

{{{
def linspace(start, stop, num=50, endpoint=True, retstep=False):
"""Return evenly spaced numbers.

Return 'num' evenly spaced samples from 'start' to 'stop'.  If
'endpoint' is True, the last sample is 'stop'. If 'retstep' is
True then return the step value used.
"""
num = int(num)
if num <= 0:
return array([], float)
if endpoint:
if num == 1:
return array([float(start)])
step = (stop-start)/float((num-1))
y = _nx.arange(0, num) * step + start
y[-1] = float(stop)
else:
step = (stop-start)/float(num)
y = _nx.arange(0, num) * step + start
if retstep:
return y, step
else:
return y
}}}

Note, the above change would have the effect of making
linspace(start,stop,1) return stop, rather than start.  If this is
considered undesirable, it's a simple matter to special case the num==1
case for backwards compatibility.  I.e.
{{{
if num>1: y[-1] = float(stop)
}}}

--
Ticket URL: <http://projects.scipy.org/scipy/numpy/ticket/264>
NumPy <http://projects.scipy.org/scipy/numpy>
The fundamental package needed for scientific computing with Python.
```