How is np.linspace() used to create an array in Python?

0216

The np.linspace() function in Python, part of the NumPy library, is used to create an array of evenly spaced values over a specified range. It is particularly useful when you need to generate a sequence of numbers with a specific number of points.

Syntax

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
  • start: The starting value of the sequence.
  • stop: The end value of the sequence.
  • num: (Optional) The number of samples to generate. Default is 50.
  • endpoint: (Optional) If True (default), stop is the last sample. If False, it is not included.
  • retstep: (Optional) If True, returns the samples and the step size between samples.
  • dtype: (Optional) The desired data type of the output array.

Example

Here’s an example of how to use np.linspace():

import numpy as np

# Create an array of 5 evenly spaced values between 0 and 10
array_linspace = np.linspace(0, 10, num=5)
print(array_linspace)

Output

[ 0.   2.5  5.   7.5 10. ]

In this example, np.linspace() generates an array with 5 values evenly spaced between 0 and 10.

0 Comments

no data
Be the first to share your comment!