14.4 C
London
Wednesday, June 4, 2025
HomePandas in PythonGeneral Functions in PythonHow to Calculate the Magnitude of a Vector Using NumPy

How to Calculate the Magnitude of a Vector Using NumPy

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories