NumPy is a powerful Python library for numerical computing, and np.linspace()
is one of the most useful functions for generating arrays of evenly spaced values within a specified range.
In previous tutorials, we learned about Key Features of NumPy Arrays in Python. This tutorial will provide a step-by-step guide to understand how to use np.linspace()
effectively, with examples.
np.linspace()
to Create Arrays with Evenly Spaced Numbers
The np.linspace()
function in NumPy is used to create arrays containing evenly spaced numbers over a specified range. It is particularly useful when you need a specific number of points between a given start and stop value.
Syntax => numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
start
(required) – This is the starting value of the sequence. This value can be of float or int data-type.stop
(required) – This is the end value of the sequence. This value can be of float or int data-type.num
(optional) – The number of evenly spaced samples to generate. This value can be of positive int data-type. Default is 50.endpoint
(optional) – This is of bool data-type. IfTrue
(default),stop
is included in the output. IfFalse
, the sequence ends just beforestop
.retstep
(optional) – This is of bool data-type. IfTrue
, returns a tuple(samples, step)
, wherestep
is the spacing between the values.dtype
(optional) – The data-type of the output array. IfNone
(default), it is inferred from thestart
andstop
values.axis
(optional) – It takes the input value of the axis along which the value will be stored. Default is 0. This is of int data-type. This is more relevant when creating multi-dimensional arrays.
How Step Size is Calculated for np.linspace() Function
np.linspace(start, stop, num, endpoint)
=> This function creates the number of points which are distributed evenly between start
and stop
. This even distribution of numbers is done based on step size. Step Size Calculation for np.linspace()
is done based on a condition.
endpoint=True
=> The last value in the range will be exactly equal to stop
value. The total length of the range (from start
to stop
) will be calculated as stop - start
, and dividing it into num - 1
equal intervals (because the last point is already included). => Step Size Calculation (endpoint=True
) = (stop - start)/(num - 1)
- Example:
np.linspace(0, 18, num=10, endpoint=True)
- The last value in this range will be exactly equal to 18. The total length of the range (from 0 to 18) will be calculated as (18 – 0) = 18. Dividing it into (10 – 1) = 9 equal intervals (because the last point is already included).
- Step Size = (18 – 0)/(10 – 1) = 18/9 = 2
- Output Array =>
[ 0. 2. 4. 6. 8. 10. 12. 14. 16. 18.]
endpoint=False
=> The last value in the range will exclude the stop
value. The total length of the range (from start
to stop
) will be calculated as stop - start
, and dividing it into num
equal intervals (because the last point is excluded). => Step Size Calculation (endpoint=False
) = (stop - start)/(num)
- Example:
np.linspace(0, 18, num=10, endpoint=False
- The last value in this range will exclude value 18. The total leangth of the range (from 0 to 18) will be calculated as (18 – 0) = 18. Dividing it into 10 equal intervals (because the last point is excluded)
- Step Size = (18 – 0)/(10) = 18/10 = 1.8
- Output Array =>
[ 0. 1.8 3.6 5.4 7.2 9. 10.8 12.6 14.4 16.2]
- Step Size Calculation for
endpoint=True
=(stop - start)/(num - 1)
- Step Size Calculation for
endpoint=False
=(stop - start)/(num)
np.linspace()
to Create Array with Default Parameters
import numpy as np
linspace_array_1 = np.linspace(0, 20) # Generate 50 points between 0 and 20
print(linspace_array_1)
# Output
# [ 0. 0.40816327 0.81632653 1.2244898 1.63265306 2.04081633
# 2.44897959 2.85714286 3.26530612 3.67346939 4.08163265 4.48979592
# 4.89795918 5.30612245 5.71428571 6.12244898 6.53061224 6.93877551
# 7.34693878 7.75510204 8.16326531 8.57142857 8.97959184 9.3877551
# 9.79591837 10.20408163 10.6122449 11.02040816 11.42857143 11.83673469
# 12.24489796 12.65306122 13.06122449 13.46938776 13.87755102 14.28571429
# 14.69387755 15.10204082 15.51020408 15.91836735 16.32653061 16.73469388
# 17.14285714 17.55102041 17.95918367 18.36734694 18.7755102 19.18367347
# 19.59183673 20. ]
The default behavior of np.linspace()
is to generate an array with 50 evenly spaced values between start
(0) and stop
(10). The endpoint=True
option means that 20 is included as the last value.
np.linspace()
– Create Array with Specified Number of Points (num
)
import numpy as np
linspace_array_2 = np.linspace(0, 18, num=10) # Generate 10 points between 0 and 18
print(linspace_array_2)
# Output => [ 0. 2. 4. 6. 8. 10. 12. 14. 16. 18.]
linspace_array_3 = np.linspace(0, 18, num=-10) # Negative value for num
print(linspace_array_3)
# Output => ValueError: Number of samples, -10, must be non-negative.
np.linspace(0, 18, num=10)
=> Thenum
parameter controls how many points you want betweenstart
andstop
. Here, we requestednum
(10) points, which gives an array of 10 values evenly spaced betweenstart
(0) andstop
(18). Theendpoint=True
(default) option means that 18 is included as the last value. This will create an array[ 0. 2. 4. 6. 8. 10. 12. 14. 16. 18.]
of float data-type.np.linspace(0, 18, num=-10)
=> In this case, we have defined negative value tonum
(-10). This will raise an errorValueError
: Number of samples, -10, must be non-negative.
np.linspace()
– Create Array Excluding the stop
Value using endpoint=False
import numpy as np
linspace_array_4 = np.linspace(0, 18, num=10, endpoint=False) # Exclude the stop value
print(linspace_array_4)
# Output => [ 0. 1.8 3.6 5.4 7.2 9. 10.8 12.6 14.4 16.2]
Setting endpoint=False
ensures that the stop
value (18 in this case) is not included in the array. The array contains 10 evenly spaced points, but the last one is less than 18. Output Array => [ 0. 1.8 3.6 5.4 7.2 9. 10.8 12.6 14.4 16.2]
np.linspace()
– Return the Step Size (retstep=True
)
import numpy as np
linspace_array_5, step_size = np.linspace(0, 12, num=6, endpoint=True, retstep=True) # Return both the array and step size
print("Array:", linspace_array_5)
print("Step size:", step_size)
# Output => Array: [ 0. 2.4 4.8 7.2 9.6 12. ]
# Step size: 2.4
linspace_array_6, step_size = np.linspace(0, 12, num=6, endpoint=False, retstep=True) # Return both the array and step size
print("Array:", linspace_array_6)
print("Step size:", step_size)
# Output => Array: [ 0. 2. 4. 6. 8. 10.]
# Step size: 2.0
With retstep=True
, np.linspace()
returns a tuple with the array and the step size. The step size is the difference between consecutive numbers in the array.
np.linspace(0, 12, num=6, endpoint=True, retstep=True)
=> Withendpoint=True
, returned step size is 2.4np.linspace(0, 12, num=6, endpoint=False, retstep=True)
=> Withendpoint=False
, returned step size is 2.0
np.linspace()
– Specify a Different Data Type (dtype
)
import numpy as np
linspace_array_7 = np.linspace(0, 12, num=6, dtype=str) # Array with string data-type
print("String Array:", linspace_array_7)
# Output => String Array: ['0.0' '2.4' '4.8' '7.199999999999999' '9.6' '12.0']
linspace_array_8 = np.linspace(0, 12, num=6, dtype=bool) # Array with boolean data-type
print("Boolean Array:", linspace_array_8)
# Output => Boolean Array: [False True True True True True]
linspace_array_9 = np.linspace(0, 12, num=6, dtype=complex) # Array with complex data-type
print("Complex Array:", linspace_array_9)
# Output => Complex Array: [ 0. +0.j 2.4+0.j 4.8+0.j 7.2+0.j 9.6+0.j 12. +0.j]
linspace_array_10 = np.linspace(0, 12, num=6, dtype=int) # Array with integer data-type
print("Integer Array:", linspace_array_10)
# Output => Integer Array: [ 0 2 4 7 9 12]
The dtype
argument forces the array to store numbers in given data-type, even though the numbers in the sequence are floats by default.
np.linspace(0, 12, num=6, dtype=str)
=> Returns an array with string data-type elements =>['0.0' '2.4' '4.8' '7.199999999999999' '9.6' '12.0']
np.linspace(0, 12, num=6, dtype=bool)
=> Returns an array with boolean data-type elements. Boolean isFalse
for number 0 andTrue
for non-zero numbers. =>[False True True True True True]
np.linspace(0, 12, num=6, dtype=complex)
=> Returns an array with complex data-type elements. Number value is real part of complex and imaginary part is 0 =>[ 0. +0.j 2.4+0.j 4.8+0.j 7.2+0.j 9.6+0.j 12. +0.j]
np.linspace(0, 12, num=6, dtype=int)
=> Returns an array with integer data-type elements. The numbers generated will be integers, so any fractional values will be truncated. =>[ 0 2 4 7 9 12]
np.linspace()
Create Array in Descending Order using We can create array in descending order using np.linspace()
function.
- If
start < stop
=> Array elements will be in ascending order - if
start = stop
=> Array with constant elements - If
start > stop
=> Array elements will be in descending order
import numpy as np
linspace_array_11 = np.linspace(-8, 9, num=6) # Array start with -8 (negative) and stop at 9 (positive)
print("Array:", linspace_array_11)
# Output => Array: [-8. -4.6 -1.2 2.2 5.6 9. ] (elements in ascending order)
linspace_array_12 = np.linspace(-8, -1, num=6) # Array start with -8 (negative) and stop at -1 (negative)
print("Array:", linspace_array_12)
# Output => Array: [-8. -6.6 -5.2 -3.8 -2.4 -1. ] (elements in ascending order)
linspace_array_13 = np.linspace(8, -1, num=6) # Array start with 8 (positive) and stop at -1 (negative)
print("Array:", linspace_array_13)
# Output => Array: [ 8. 6.2 4.4 2.6 0.8 -1. ] (elements in descending order)
linspace_array_14 = np.linspace(8, 8, num=6) # Array start = stop
print("Array:", linspace_array_14)
# Output => Array: [8. 8. 8. 8. 8. 8.]
In this example, we will see how array elements can be in ascending or descending order based on positive and negative value for start
and stop
attributes.
np.linspace(-8, 9, num=6)
=>start
(negative) is less thanstop
(positive) => Array elements in ascending order =>[-8. -4.6 -1.2 2.2 5.6 9. ]
np.linspace(-8, -1, num=6)
=>start
(negative) is less thanstop
(negative) => Array elements in ascending order =>[-8. -6.6 -5.2 -3.8 -2.4 -1. ]
np.linspace(8, -1, num=6)
=>start
(positive) is greater thanstop
(negative) => Array elements in descending order =>[ 8. 6.2 4.4 2.6 0.8 -1. ]
np.linspace(8, 8, num=6)
=> In this casestart
is equal tostop
=> Array will be of constant values =>[8. 8. 8. 8. 8. 8.]
N-Dimensional Array using np.linspace()
import numpy as np
# Create a 1-D array with 5 evenly spaced numbers between 0 and 80
linspace_array_15 = np.linspace(0, 80, num=5) # 5 values spaced along the interval 0 to 80
# Now we create a 2-D 3x5 array where each row has these values spaced along axis=1
linspace_array_2d = np.tile(linspace_array_15, (3, 1)) # Repeat the array 3 times along axis 0 (rows)
print(linspace_array_2d)
# Output
# [[ 0. 20. 40. 60. 80.]
# [ 0. 20. 40. 60. 80.]
# [ 0. 20. 40. 60. 80.]]
# Now we create a 3-D 3x5*2 array
linspace_array_3d = np.tile(linspace_array_15, (3, 1, 2)) # Repeat the 2-D array 3 times along axis 0 (rows)
print(linspace_array_3d)
# Output
# [[[ 0. 20. 40. 60. 80. 0. 20. 40. 60. 80.]]
# [[ 0. 20. 40. 60. 80. 0. 20. 40. 60. 80.]]
# [[ 0. 20. 40. 60. 80. 0. 20. 40. 60. 80.]]]
np.linspace(0, 80, num=5)
=> This creates a 1-D array with 5 evenly spaced numbers alongaxis = 0
.np.tile(linspace_array_15, (3, 1))
=> This creates 2-D array, repeat the 1-D array 3 times along axis 0 (rows)np.tile(linspace_array_15, (3, 1, 2))
=> This creates 3-D array, repeat the 2-D array 3 times along axis 0 (rows)
np.linspace()
Plot Shapes & Curves using We can use Python’s matplotlib library to plot the shapes and curves using values generated via np.linspace()
function. np.linspace()
function can generate the x-values (or even y-values) in a smooth, controlled manner.
- Spiral – A spiral can be created using polar coordinates. The radius increases linearly as the angle (theta) increases.
- Sine Wave – The sine wave can be plotted using the equation
y = sin(x)
. We can generate values forx
usingnp.linspace()
and then calculatey = sin(x)
. - Ellipse – An ellipse can be plotted using the parametric equations =>
x = a * cos(θ)
;y = b * sin(θ)
Wherea
andb
are the semi-major and semi-minor axes of the ellipse. - Parabola – A simple parabola can be plotted using the equation
y = x2
. We’ll usenp.linspace()
to create the x-values, and then calculate the corresponding y-values. - Circle – To plot a circle, we can parameterize it using trigonometric functions (sine and cosine). Here’s an example:
np.linspace()
Program to Plot Spiral using import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 4 * np.pi, 1000) # Generate theta values (angle) from 0 to 4*pi
r = theta # Generate radius values that increase linearly with theta
# Parametric equations for the spiral
x = r * np.cos(theta)
y = r * np.sin(theta)
# Plot the spiral
plt.plot(x, y)
plt.title("Spiral: r = θ")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.gca().set_aspect('equal', adjustable='box') # Equal aspect ratio for proper spiral shape
plt.show()
np.linspace()
Program to Plot Sine Wave using import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 4 * np.pi, 1000) # Generate x values from 0 to 4*pi
y = np.sin(x) # Sine function
# Plot the sine wave
plt.plot(x, y)
plt.title("Sine Wave: y = sin(x)")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()
Conclusion
The np.linspace()
is a versatile and key function for generating arrays of evenly spaced numbers. It is generally good when one needs control over the number of points given in a range. Understanding these key parameters like start
, stop
, num
, and endpoint
will help you craft arrays for your needs and can be used with scientific data, visualizations, and mathematical computations. Key points:
- The
np.linspace()
function generates evenly spaced values. - You can control the number of values with
num
parameter. - The
endpoint
parameter decides whether thestop
value is included. retstep
helps you get the step size between values.dtype
lets you define the data-type of the output array.
Code snippets and programs related to np.linspace()
: Create Arrays with Evenly Spaced Numbers in NumPy, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in NumPy tutorial.
Related Topics
- Introduction to NumPy: Core Features and Importance in different FieldsIntroduction to NumPy NumPy stands for Numerical Python. It is an open-source Python library, which is predominantly mostly used for numerical computations in Python. It provides mathematical functions applicable to work with multi-dimensional arrays and matrices. It is a powerful tool to handle large data structures and allows performing complex arithmetic calculations. It has built-in computational features…
- How to Install NumPy on Windows, Linux and Mac: step-by-step guideWe can install NumPy on all major operating systems such as Windows, Linux and macOS. NumPy installation process is very simple and can be done using pip, which is the Python package installer. Here are the steps to install NumPy on Windows, Linux and Mac operating systems. Install NumPy on Windows, Linux and Mac Prerequisites…
- NumPy Array in Python: First Step into Numerical PythonNumPy array in Python are basic entities for numerical computations. They originate from the NumPy library, an essential package in Python for scientific computing. A NumPy array also termed as ndarray, is highly efficient and an object of multi-dimensional array (N-dimensional array), which provides the base functions of numerical operations. Being NumPy Arrays an essential…
- numpy.array(): Create NumPy Arrays using Lists, Tuples and Arrays (with Example Programs)NumPy (Numerical Python) is one of the most powerful libraries for numerical computations, data manipulation, and analysis in Python. At the core of NumPy is the ndarray, a multi-dimensional or N-dimensional array that allows to store and manipulate large datasets efficiently. NumPy provides several ways to create arrays, from simple ones to more complex multi-dimensional…
- Create Arrays with Predefined Values using np.zeros(), np.ones(), np.full() and np.empty()Create Arrays with Predefined Values NumPy library provides various functions to create arrays with predefined values. While creating an array, these NumPy functions helps to initialize the arrays with initial values. In last tutorial, we learned about Key Features of NumPy Arrays in Python. In this article, we will learn about 4 functions to create…