AppDividend
Latest Code Tutorials

np.linspace: How to Create Evenly or Non-Evenly Spaced Arrays

The np.linspace() is a numpy function that returns the sequence of numbers in a specified interval. The np.linspace() function mainly requires the start end and the number of splits. The np.linspace() function returns the n numbers between the two numbers by equally splitting the numbers.

Syntax

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)

Arguments

start: It is the starting number for the sequence.

stop: It is the ending number for the sequence.

num: It is the total number of samples to generate. It is the number of splitting we have to make between two numbers. 

endpoint: If this endpoint is true, then the stop is the ending value, or else this stop value will not be included in the sequence. True is the default value for the endpoint argument. But if we change it to false, the step size also changes.

Retstep: It stands for return step. It is set to False by default. If we change the value to True, then the function returns the size of the step along with the sample generated. 

Dtype: It stands for the data type. It is set to None as default. We can mention the data type in this argument. For example, if we want to split the numbers only in a rounded manner, we can give it as int. We have to mention the data type correctly. If we don’t have any required data type, this argument should not be filled. 

Axis: It is the direction in which the data is needed to be inserted. By default, it is set to 0. There are two types 0 for inserting in the beginning and -1 for inserting in the end.

How to Create Evenly or Non-Evenly Spaced Arrays in Python

To create evenly or non-evenly spaced arrays in Python, use the np.linspace() function.

import numpy as np

# Assigning the sequence created to the variable named sample
sample = np.linspace(1.0, 2.0, 10, endpoint=False)
print(sample)

Output

[1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9]

In this output, we can see that the function returns evenly spaced numbers over an interval of 0.1. 

In this program, we imported the numpy package. The numpy package is used for numerical calculations. Then we used the linspace function to create the sequence. In this function, the starting element is 1, and the ending element is 2; the step size is 10.

Hence, it is a sequence of numbers that we split these numbers to the number of splits mentioned.

# Importing Numpy as np
import numpy as np

# Assigning the sequence created to the variable named sample
sample = np.linspace(1.0, 2.0, 10, endpoint=False, retstep=True, axis=0)
print(sample)

Output

(array([1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9]), 0.1)

That’s it for this tutorial.

Related posts

np.linalg.inv

np.linalg.svd

np.linalg.solve

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.