w3resource

NumPy: Get the magnitude of a vector in NumPy


Find Magnitude of Vector

Write a NumPy program to get the magnitude of a vector in NumPy.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'x' containing integers
x = np.array([1, 2, 3, 4, 5])

# Printing a message indicating the original array will be displayed
print("Original array:")

# Printing the original array 'x' with its elements
print(x)

# Printing a message indicating the calculation of the magnitude of the vector
print("Magnitude of the vector:")

# Calculating the magnitude (L2 norm) of the vector 'x' using np.linalg.norm() function
magnitude = np.linalg.norm(x)

# Printing the calculated magnitude of the vector 'x'
print(magnitude)

Sample Output:

Original array:                                                        
[1 2 3 4 5]                                                            
Magnitude of the vector:                                               
7.4161984871

Explanation:

In the above code –

x = np.array(...) – This line creates a NumPy array 'x' containing integer values 1, 2, 3, 4, and 5.

np.linalg.norm(x): Calculate the L2 (Euclidean) norm of the array 'x'. The L2 norm is the square root of the sum of the squared elements in the array. In this case, it is equivalent to the length (magnitude) of the vector 'x' in a 5-dimensional space.

print(...): Prints the calculated L2 norm.

Python-Numpy Code Editor: