[SciPy-user] linspace

Alan G Isaac aisaac at american.edu
Mon Dec 5 00:09:53 CST 2005

```>>> S.linspace(0,1,2.5)
array([ 0.        ,  0.66666667,  1.33333333])
>>> S.linspace(0,1,1)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "C:\Python24\lib\site-packages\scipy\base\function_base.py", line 91, in
linspace
step = (stop-start)/float((num-1))
ZeroDivisionError: float division

While this is just an abuse and a corner case, both of these are odd.
Therefore I suggest a new definition:

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

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

Alan Isaac

P.S. Here is the current definition:
def linspace(start,stop,num=50,endpoint=1,retstep=0):
""" Evenly spaced samples.

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

```