How to Calculate the Magnitude of a Vector Using NumPy


The magnitude of a given vector, x, is calculated as:

||x|| = √x12 + x22 + x32 + … + xn2

For example, suppose x = [3, 7, 4]

The magnitude would be calculated as:

||x|| = √32 + 72 + 42 = √74 = 8.602

You can use one of the following two methods to calculate the magnitude of a vector using the NumPy package in Python:

Method 1: Use linalg.norm()

np.linalg.norm(v)

Method 2: Use Custom NumPy Functions

np.sqrt(x.dot(x))

Both methods will return the exact same result, but the second method tends to be much faster especially for large vectors.

The following example shows how to use each method in practice.

Method 1: Use linalg.norm()

The following code shows how to use the np.linalg.norm() function to calculate the magnitude of a given vector:

import numpy as np

#define vector
x = np.array([3, 6, 6, 4, 8, 12, 13])

#calculate magnitude of vector
np.linalg.norm(x)

21.77154105707724

The magnitude of the vector is 21.77.

Method 2: Use Custom NumPy Functions

The following code shows how to use custom NumPy functions to calculate the magnitude of a given vector:

import numpy as np

#define vector
x = np.array([3, 6, 6, 4, 8, 12, 13])

#calculate magnitude of vector
np.sqrt(x.dot(x))

21.77154105707724

The magnitude of the vector is 21.77.

Notice that this matches the value that we calculated using the previous method.

Additional Resources

The following tutorials explain how to perform other common operations using NumPy:

How to Map a Function Over a NumPy Array
How to Add a Column to a NumPy Array
How to Convert NumPy Array to List in Python

Leave a Reply

Your email address will not be published.