Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have a linspace function in its std lib?

Tags:

python

matlab

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.

like image 200
mjgpy3 Avatar asked Sep 08 '12 20:09

mjgpy3


People also ask

Does Python have Linspace?

linspace is an in-built function in Python's NumPy library. It is used to create an evenly spaced sequence in a specified interval.

What is the equivalent of Linspace in Python?

The NumPy linspace function (sometimes called np. linspace) is a tool in Python for creating numeric sequences. It's somewhat similar to the NumPy arange function, in that it creates sequences of evenly spaced numbers structured as a NumPy array.

What is Linspace in Python NumPy?

The numpy. linspace() function returns number spaces evenly w.r.t interval.

What does Linspace function do?

The linspace function generates linearly spaced vectors. It is similar to the colon operator ":", but gives direct control over the number of points. y = linspace(a,b) generates a row vector y of 100 points linearly spaced between and including a and b.


2 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.

like image 183
Katriel Avatar answered Sep 20 '22 06:09

Katriel


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.

like image 45
Sven Marnach Avatar answered Sep 21 '22 06:09

Sven Marnach