This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 8: NumPy recap and exercises

Compute a unit vector

face Joe Stacey Josiah Wang

A question using vectors!

Challenge #3

Use NumPy to compute the unit vector for x below.

A unit vector is computed by dividing a vector by its length, or more specifically its L_2 norm \left\Vert x \right\Vert_2 = \sqrt{x^2_1 + x^2_2 = ... + x^2_n}.

import numpy as np

x = np.array([3, 5, 1, 2, 4])
unit_x = ????
assert np.all(np.isclose(
                unit_x,
                np.array([0.40451992, 0.67419986, 0.13483997, 
                          0.26967994, 0.53935989])
       ))

One possible solution

import numpy as np

x = np.array([3, 5, 1, 2, 4])
norm = np.sqrt((x**2).sum())
unit_x = x / norm

Other ways of computing the L_2-norm

norm = np.sqrt(np.sum(np.square(x)))
norm = np.linalg.norm(x)