Does Python have a linspace function in its std lib?
Question:
Does Python have a function like matlab’s linspace
in its standard library?
If not, is there an easy way to implement it without installing an external package?
Here’s a quick and easy definition of linspace in matlab terms.
Note
I don’t need a “vector result” as defined by the link, a list will do fine.
Answers:
No, it doesn’t. You can write your own (whicn isn’t difficult), but if you are using Python to fulfil some of matlab’s functionality then you definitely want to install numpy
, which has numpy.linspace
.
You may find NumPy for Matlab users informative.
The easiest way to implement this is a generator function:
from __future__ import division
def linspace(start, stop, n):
if n == 1:
yield stop
return
h = (stop - start) / (n - 1)
for i in range(n):
yield start + h * i
Example usage:
>>> list(linspace(1, 3, 5))
[1.0, 1.5, 2.0, 2.5, 3.0]
That said, you should definitely consider using NumPy, which provides the numpy.linspace()
function and lots of other features to conveniently work with numerical arrays.
You can define a function to do this:
def linspace(a, b, n=100):
if n < 2:
return b
diff = (float(b) - a)/(n - 1)
return [diff * i + a for i in range(n)]
As long as the spacing is > 1, this is the Python equivalent to the following MATLAB function call: linspace(start,stop,spacing)
start = 5
stop = 6
spacing = int(11)
linspace = [start + float(x)/(spacing-1)*(stop-start) for x in range(spacing)]
Does Python have a function like matlab’s linspace
in its standard library?
If not, is there an easy way to implement it without installing an external package?
Here’s a quick and easy definition of linspace in matlab terms.
Note
I don’t need a “vector result” as defined by the link, a list will do fine.
No, it doesn’t. You can write your own (whicn isn’t difficult), but if you are using Python to fulfil some of matlab’s functionality then you definitely want to install numpy
, which has numpy.linspace
.
You may find NumPy for Matlab users informative.
The easiest way to implement this is a generator function:
from __future__ import division
def linspace(start, stop, n):
if n == 1:
yield stop
return
h = (stop - start) / (n - 1)
for i in range(n):
yield start + h * i
Example usage:
>>> list(linspace(1, 3, 5))
[1.0, 1.5, 2.0, 2.5, 3.0]
That said, you should definitely consider using NumPy, which provides the numpy.linspace()
function and lots of other features to conveniently work with numerical arrays.
You can define a function to do this:
def linspace(a, b, n=100):
if n < 2:
return b
diff = (float(b) - a)/(n - 1)
return [diff * i + a for i in range(n)]
As long as the spacing is > 1, this is the Python equivalent to the following MATLAB function call: linspace(start,stop,spacing)
start = 5
stop = 6
spacing = int(11)
linspace = [start + float(x)/(spacing-1)*(stop-start) for x in range(spacing)]