Examples of numpy.linspace() in Python
( 26 Articles)
The numpy.linspace() function returns an ndarray with equally spaced intervals between the start and stop values. That ndarray is a vector space, also known as a linear space. That’s why the function is named linspace.
This article goes over the syntax as well as a few examples of using the numpy.linspace() function in Python programs.
At first, let’s take a look at numpy.linspace() syntax:
numpy.linspace( start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0 )
|start||required||The starting value of the sequence.|
|stop||required||The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.|
|num||optional||50||Number of samples to generate. Must be non-negative integer.|
|endpoint||optional||True||If True, stop is the last sample. Otherwise, it is not included.|
|retstep||optional||False||If True, return (samples, step), where step is the spacing between samples.|
|dtype||optional||None||The type of the output array.|
|axis||optinal||0||The axis in the result to store the samples. Relevant only if start or stop are array-like. By default, the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end.|
Example 1: Basic Usage
import numpy as np x1 = np.linspace(start = 0, stop = 100, num = 11) print(x1) # set endpoint to False x2 = np.linspace(start = 0, stop = 100, num = 11, endpoint = False) print(x2) # set retstep to True x3 = np.linspace(0, 100, num = 11, retstep = True) print(x3)
Output (x1, x2, and x3 in the corresponding order):
[ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] [ 0. 9.09090909 18.18181818 27.27272727 36.36363636 45.45454545 54.54545455 63.63636364 72.72727273 81.81818182 90.90909091] (array([ 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.]), 10.0)
Example 2: Making a bar chart with np.linspace() and Matplotlib
import numpy as np import matplotlib.pyplot as plt N = 11 x = np.linspace(0, 100, num = N) y = x ** 3 - 2 * x + 7 ax = plt.subplot() ax.bar(x, y, width=4) ax.set_xlabel('X') ax.set_ylabel('Y') plt.show()
Example 3: endpoint = True vs endpoint = False graphical representation
import numpy as np import matplotlib.pyplot as plt N = 9 x1 = np.linspace(0, 8, num = N) x2 = np.linspace(0, 8, num = N, endpoint = False) y = np.ones(N) plt.plot(x1, y, 'o') plt.plot(x2, y + 1, 'o') plt.ylim([0, 3]) plt.show()
At this point you should have a better understanding of some of major use cases of np.linspace(). If you’d like to learn more about NumPy and Python, please check out our NumPy topic page and Python category page for more tutorials and quick examples.