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:
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.