How to calculate magnitude of vector in NumPy

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.

  1. Using NumPy
  2. Using Dot Product and Square-root
  3. Using Einstein Summation
  4. 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

Free Learning Resources

Leave a Comment

Your email address will not be published.