You can calculate the magnitude of a vector in NumPy with the following methods. If you want to learn Python, I highly recommend reading This Book. In this article, I will cover 4 methods to calculate the magnitude of a vector in Python.
- Using NumPy
- Using Dot Product and Square-root
- Using Einstein Summation
- Using SciPy
Method 1: Using NumPy
# Import the NumPy library as np import numpy as np # Initialize a Vector a = np.array([3, 4]) # Find Magnitude magnitude = np.linalg.norm(a) # Display the Magnitude print(magnitude)
Output:
5.0
Method 2: Using Dot Product and Square-root
# Import the NumPy library as np import numpy as np # Initialize a Vector a = np.array([3, 4]) # Find Magnitude magnitude = np.sqrt(a.dot(a)) # Display the Magnitude print(magnitude)
Output:
5.0
Method 3: Using Einstein Summation
# Import the NumPy library as np import numpy as np # Initialize a Vector a = np.array([3, 4]) # Find Magnitude magnitude = np.sqrt(np.einsum('a, a', a, a)) # Display the Magnitude print(magnitude)
Output:
5.0
Method 4: Using SciPy
from scipy import linalg as LA # Initialize a Vector a = np.array([3, 4]) # Find Magnitude magnitude = LA.norm(a) # Display the Magnitude print(magnitude)
Output:
5.0