Monday, January 20, 2025
HomeProgrammingHow can you normalize a NumPy array to create a unit vector?

How can you normalize a NumPy array to create a unit vector?

To normalize a NumPy array to a unit vector, divide the array by its magnitude (or Euclidean norm). First, compute the norm using numpy.linalg.norm(), then divide the array by this value. Here’s how you can do it:

See also  How to Convert int to string in C++

import numpy as np

# Example array
arr = np.array([3, 4])

# Compute the norm
norm = np.linalg.norm(arr)

# Normalize the array
unit_vector = arr / norm

print(unit_vector)

This results in a unit vector where the magnitude is 1. Normalizing ensures the vector retains its direction but with a length of 1.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x