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.
For more Practice: Solve these Related Problems:
- Write a NumPy program to compute the Euclidean norm (magnitude) of a vector using np.linalg.norm.
- Create a function that calculates the magnitude of a vector and verifies it with a manual square-root computation.
- Test the magnitude calculation on vectors of various dimensions and compare with built-in norm functions.
- Implement the magnitude computation using both np.sqrt and element-wise squaring to validate the result.
Python-Numpy Code Editor:
Previous: Write a NumPy program to select indices satisfying multiple conditions in a NumPy array.Next: Write a NumPy program to count the frequency of unique values in NumPy array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics