Understanding NumPy’s linspace
The linspace
function, short for “linearly spaced,” creates a sequence of numbers evenly distributed between a specified start and end point. It takes three primary arguments:
- start: The starting value of the sequence.
- stop: The end value of the sequence. Note that the
stop
value is included in the generated array. - num: The number of samples to generate. This determines the total number of elements in the resulting array.
The function returns a NumPy array containing the evenly spaced numbers.
Basic Usage
The simplest application of linspace
involves creating a basic sequence:
import numpy as np
= np.linspace(0, 1, 5)
evenly_spaced_numbers print(evenly_spaced_numbers)
This generates an array with five elements, spaced equally between 0 and 1.
Controlling the Endpoint
By default, linspace
includes the stop
value. If you need to exclude it, you can use np.linspace(start, stop, num, endpoint=False)
:
= np.linspace(0, 1, 5, endpoint=False)
evenly_spaced_numbers_exclusive print(evenly_spaced_numbers_exclusive)
Applications in Plotting
linspace
is frequently used to generate x-coordinates for plotting functions:
import matplotlib.pyplot as plt
= np.linspace(0, 2 * np.pi, 100)
x = np.sin(x)
y
plt.plot(x, y)"x")
plt.xlabel("sin(x)")
plt.ylabel("Sine Wave")
plt.title( plt.show()
This code generates 100 evenly spaced points between 0 and 2π, providing a smooth representation of the sine wave.
Creating Sequences with Non-Integer Steps
While linspace
focuses on the number of samples, you can indirectly control the step size by adjusting the num
parameter. For example, to approximate a step size of 0.1 between 0 and 1, you might use:
= np.linspace(0, 1, 11) # 11 points to include 0 and 1
approximate_step print(approximate_step)
This demonstrates how to achieve nearly equally spaced numbers, even without explicitly defining the step size.
Beyond the Basics: Reshaping and Further Manipulation
The array generated by linspace
can be further manipulated using other NumPy functions. For instance, you can reshape it into different dimensions using reshape()
:
= np.linspace(0, 1, 10).reshape(2, 5)
reshaped_array print(reshaped_array)
This showcases the flexibility of integrating linspace
within a broader NumPy workflow. This allows for powerful array manipulations and computations based on evenly-spaced numerical sequences.