Understand Numpy Linspace() Method

by Sudipta Deb | Dec 11, 2024 | Data Science, Data Visualization, Numpy, Python | 0 comments

Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

NumPy is a fundamental package in the Python data science environment, providing a comprehensive range of functions for the efficient manipulation of numerical data. The linspace() function is frequently employed to produce uniformly distributed numbers within a defined interval, rendering it an invaluable resource for activities necessitating exact numerical ranges, such as data visualization and mathematical modeling. 

The linspace() method in NumPy produces an array of uniformly distributed values within a specified range. 

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

Parameters:

  • start: [optional] start of interval range. By default start = 0
  • stop: end of interval range
  • num: [int, optional] No. of samples to generate
  • retstep: If True, Stop is the last sample By default restep = False
  • endpoint: If True, stop is included as the last value. If False, stop is excluded. By default  endpoint=True.
  • dtype: type of output array
  • axis: If start and stop are arrays, axis specifies on what axis will the values be added. If axis = 0, value is added to front, if  axis = -1 value is added at the end.

Return:

  • ndarray
  • step : [float, optional], if restep = True

The form you have selected does not exist.

Sample Code

I normally put all my codes in my personal Github repository, so that I can easily share with others. Here is the Github Code Repo where you can find the code samples used in this blog post.

linspace_function.ipynb

Basic Example

Here, for example, we create an array that starts at 0 and ends at 500, throughout an interval of 25 numbers. As you can expect, it returns an array with 

[ 0. , 20.83333333, 41.66666667, 62.5 , 83.33333333, 104.16666667, 125. , 145.83333333, 166.66666667, 187.5 , 208.33333333, 229.16666667, 250. , 270.83333333, 291.66666667, 312.5 , 333.33333333, 354.16666667, 375. , 395.83333333, 416.66666667, 437.5 , 458.33333333, 479.16666667, 500. ]

import numpy as np
data = np.linspace(0, 500, 25)
data

Create 1D Arrays

The below code will create an array of 15 evenly spaced numbers between 0 and 20.

# Create an array of 15 evenly spaced numbers between 0 and 20
data = np.linspace(0, 20, num = 15)
data

Here is the output:   array([ 0. , 1.42857143, 2.85714286, 4.28571429, 5.71428571, 7.14285714, 8.57142857, 10. , 11.42857143, 12.85714286, 14.28571429, 15.71428571, 17.14285714, 18.57142857, 20. ])

Get The Array And Step Size

While generating the array of evenly spaced numbers between two numbers, we can get back the step size as well. Below code set not only stores the array,  but at the same time, stores the step size as well.

# Get the array and step size together
data, step_size = np.linspace(0 , 100 , num=25, retstep=True)
print("Returned Array: ", data)
print("Step Size: ", step_size)

Here comes the output:

Returned Array: [ 0. 4.16666667 8.33333333 12.5 16.66666667 20.83333333 25. 29.16666667 33.33333333 37.5 41.66666667 45.83333333 50. 54.16666667 58.33333333 62.5 66.66666667 70.83333333 75. 79.16666667 83.33333333 87.5 91.66666667 95.83333333 100. ]

Step Size: 4.166666666666667

Let's Create 2D Array

The below example code generates 2 arrays  where the first will contain three numbers between 10 and 20, whereas the second will contain three numbers between 15 and 25. This will generate the 2D array.

# Perform column-wise linear interpolation from [10, 20] to [15, 25] over 3 steps
new_array = np.linspace([10, 20], [15, 25], num=3, axis=1)
print("New Array: \n",new_array)

Here is the output which is none other than a 2D array.

New Array: [[10. 12.5 15. ] [20. 22.5 25. ]]

Difference Between Numpy Arange() and Linspace()

np.linspace allows you to define how many values you will get, including the specified min and max value. It infers the stepsize. 

np.arange allows you to define the stepsize and infers the number of steps (the number of values you get. It excludes the maximum value unless rounding error makes it do otherwise.

#np.arange(start, stop, step)
np.arange(0, 10 , 2)        # Will produce array([0, 2, 4, 6, 8])
#np.linspace(start,stop,number)
np.linspace(0, 10 , 2)     # Will produce array([ 0., 10.])

Final Thoughts

NumPy's linspace() function is a fundamental tool in the data science toolkit, offering precision and flexibility in generating numerical sequences.

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

0 Comments

Leave a Reply

Written by Sudipta Deb

Enterprise Cloud Architect, Content Creator, 20x Salesforce Certified, 1x Google Cloud Certified, 2x Copado Certified

Related Posts

4 Important Probability Distributions – Normal, Binomial, Poisson, Bernoulli

4 Important Probability Distributions – Normal, Binomial, Poisson, Bernoulli

A probability distribution specifies the likelihood of all possible outcomes of a random variable. The distribution may be classified as either continuous or discrete based on the values assumed by a random variable. Various forms of probability distributions exist. In this post, I will examine Normal, Binomial, Poisson and Bernoulli distribution and demonstrate how to utilize Python to plot it.

read more...

0 Comments

Leave a Reply