NumPy: Get the magnitude of a vector in NumPy
NumPy: Array Object Exercise-93 with Solution
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/python-numpy-exercise-93.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics