*56*

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

||x|| = âˆšx_{1}^{2} + x_{2}^{2} + x_{3}^{2} + â€¦ + x_{n}^{2}

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

The magnitude would be calculated as:

||x|| = âˆš3^{2} + 7^{2} + 4^{2} = âˆš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