Python has complex numbers built in: 3 + 4j is the number with real part 3 and imaginary part 4 (Python writes the imaginary unit i as 1j, and 1j * 1j == -1). Draw z = x + iy as an arrow from the origin to the point (x, y). In Python, z.real is x, z.imag is y, abs(z) is the arrow's length |z| = \sqrt{x^2 + y^2} (the modulus), and z.conjugate() is the mirror image \bar z = x - iy.
The weight of an arrow is its modulus squared:
It is never negative, even though z^2 can be: (1j)^2 = -1, while |1j|^2 = 1.
Write weights(zs) that returns a pair:
- the list of the weights |z|^2 of the numbers in
zs, in order, as real numbers, - the list of their shares: each weight divided by the total of all the weights, so the shares add up to 1.
Later in this path, a list like zs will describe a quantum state, and these shares will be the probabilities of its outcomes.
Examples
Input: zs = [3+4j, 1j, 0]
Output: ([25.0, 1.0, 0.0], [0.9615384615384616, 0.038461538461538464, 0.0])
Explanation: |3+4j|^2 = 9 + 16 = 25 and |1j|^2 = 0 + 1 = 1. The total is 26,
so the shares are 25/26, 1/26 and 0/26.
Input: zs = [1, -1, 1j, -1j]
Output: ([1.0, 1.0, 1.0, 1.0], [0.25, 0.25, 0.25, 0.25])
Explanation: four arrows of length 1 pointing four different ways weigh the same.
A weight such as (25+0j) (a complex number with imaginary part 0) also counts as correct.
Constraints
- at least one number in
zsis not 0 - answers are compared with a tolerance of
1e-6; do not round
Goals
- Compute the modulus squared |z|^2 = x^2 + y^2 of a complex number
- See that z times its conjugate is a real number, and that z * z is not
- Turn a list of weights into shares that add up to 1