How do you get the magnitude of a vector in NumPy?

Learn, how to get the magnitude of a vector in NumPy? By Pranit Sharma Last updated : October 07, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

According to Linear algebra, an object having both direction and magnitude are known as vectors. Numpy arrays can also be used to depict a vector.

Finding the magnitude of a vector in NumPy

To get the magnitude of a vector in NumPy, we can either define a function that computes the magnitude of a given vector based on a formula or we can use the norm() method in linalg module of NumPy. Here, linalg stands for linear algebra.

The numpy.linalg.norm() method is used to get the magnitude of a vector in NumPy.

We can also pass an optional ord argument for the nth-order norm that we want.

Let us understand with the help of an example,

Python program to get the magnitude of a vector in NumPy

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([1,2,3,4,5])

# Display original array
print("Original array:\n",arr,"\n")

# Using linalg norm method
res = np.linalg.norm(arr)

# Display Result
print("Result:\n",res)

Output

The output of the above program is:

Example: How do you get the magnitude of a vector in NumPy?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.