A vector here is a Python list of complex numbers (ints and floats are allowed too). Its length (or norm) is
\|v\| = \sqrt{\sum_i |v_i|^2}
where |v_i| is the modulus of entry i, abs(v[i]) in Python: for a + bi it is \sqrt{a^2 + b^2}, so |v_i|^2 is never negative. Dividing every entry by the length gives a vector of length 1 that points the same way, a unit vector. Every state in the simulator you are building will be a unit vector, so this step comes up again and again.
Write normalise(v) that returns the list [v[0] / L, v[1] / L, ...] where L is the length of v. If every entry of v is exactly 0, the vector has no direction and cannot be normalised: return None. Any other vector is normalised, however short it is.
Examples
Input: v = [3, 4j]
Output: [0.6, 0.8j]
Explanation: |3|^2 + |4j|^2 = 9 + 16 = 25, so the length is 5.
Squaring the entries themselves would give 9 + (4j)^2 = 9 - 16 = -7, which is not a length.
Input: v = [1+1j, 1-1j]
Output: [(0.5+0.5j), (0.5-0.5j)]
Explanation: |1+1j|^2 = 2 and |1-1j|^2 = 2, so the length is sqrt(4) = 2.
Input: v = [0, 0, 0]
Output: None
Constraints
- answers are compared with a tolerance of
1e-6
Goals
- Compute the length of a complex vector from the moduli of its entries
- Divide every entry by the length to get a unit vector
- Treat the zero vector, which has no direction, as a special case