How to normalize a NumPy array to a unit vector?
To normalize a NumPy array to a unit vector, you can use the numpy.linalg.norm function to calculate the magnitude of the vector, and then divide the array by this magnitude.
To normalize a NumPy array to a unit vector, you can use the numpy.linalg.norm function to calculate the magnitude of the vector, and then divide the array by this magnitude. Here is an example code snippet:
use the numpy.linalg.norm function to calculate the magnitude of the vector
import numpy as np
# Initialize an array
arr = np.array([1, 2, 3])
# Calculate the magnitude of the vector
magnitude = np.linalg.norm(arr)
# Normalize the array by dividing by the magnitude
unit_vec = arr / magnitude
print(unit_vec)
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
This will output [0.26726124 0.53452248 0.80178373]