The Average Reading of One Qubit

expectation value · Pauli Z · Born rule · bit order · marginal probability

A chip's readout reports each measured qubit as +1 when it reads 0 and -1 when it reads 1. Averaged over many shots, the reading of qubit q tends to a number between -1 and 1 called the expectation value of Z on that qubit, written \langle Z_q\rangle. For one qubit [a, b] it is |a|^2 - |b|^2: the probability of reading 0 minus the probability of reading 1.

The state has n qubits: a list of 2^n complex amplitudes with \sum_i |a_i|^2 = 1, where amplitude i belongs to basis state i. Measuring all qubits gives basis state i with probability |a_i|^2 (the Born rule), and its index written in binary with n digits gives the bit of every qubit. Qubit 0 is the leftmost bit: in 3 qubits, |011\rangle is index 3, with qubit 0 reading 0 and qubits 1 and 2 reading 1. So

\langle Z_q\rangle = P(\text{qubit } q \text{ reads } 0) - P(\text{qubit } q \text{ reads } 1).

Write z_average(state, q) that returns \langle Z_q\rangle.

Examples

Input:  state = [0.6, 0.8], q = 0
Output: -0.28
Explanation: 0.36 - 0.64.

Input:  state = [0, 1, 0, 0], q = 0
Output: 1.0
Explanation: the state is |01>: qubit 0 (the left bit) always reads 0.

Input:  state = [0, 1, 0, 0], q = 1
Output: -1.0

Constraints

  • the state has 1 to 12 qubits; 0 <= q < n
  • answers are compared with a tolerance of 1e-6

Goals

  • Compute the expectation value of Z on one qubit of a multi-qubit state
  • Find one qubit's bit inside a basis index, with qubit 0 as the leftmost bit
  • Combine the Born-rule probabilities of many outcomes into one average
Starting Python…