Python · Exercise 1 of 6Next
Beginner
Turn a vector into a unit vector
Write a function normalise(v) that takes a NumPy vector (a 1-D array of numbers) and returns a new vector that points the same way but has length 1. To do that, divide the vector by its length. The length of a vector is its norm, which np.linalg.norm(v) gives you (Topic 14.5).
Edge case: a vector of all zeros has length 0, and dividing by 0 would give nan. For that input, return the zeros unchanged (an all-zero vector of the same size).
Then print the normalised version of np.array([3.0, 4.0]). It should print [0.6 0.8].
What Check tests
- An all-zero vector comes back as zeros, not nan
normalise([3, 4])is[0.6, 0.8]- The result has length 1
- The direction is unchanged
- The input array is not changed
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
main.py
Sign in to run your code.
Output
Press Run to see what your program prints.