In BB84, station A sends qubits to station B. A spy can intercept a qubit, measure it in a basis of her own choice and send B a fresh qubit prepared from her result. Because she does not know A's basis, she sometimes disturbs the qubit, and B then reads a wrong bit even where A's and B's bases agree. Simulate this and count the damage.
Qubits. A one-qubit state is [a_0, a_1]. Preparing bit b in basis "+" gives |b\rangle ([1, 0] or [0, 1]); in basis "x" it gives H|b\rangle, with H = \tfrac{1}{\sqrt2}\begin{pmatrix}1&1\\1&-1\end{pmatrix}, so [0.7071, 0.7071] or [0.7071, -0.7071]. Measuring in basis "+": with p_0 = |a_0|^2, draw r = rng.random(); the result is 0 if r < p0, else 1. Measuring in basis "x": apply H to the state first, then do the same. Every measurement draws exactly one number, even when its result is certain.
The run. Use rng = random.Random(seed). For each of the n positions, in this order:
- A's bit: draw
r; the bit is 0 ifr < 0.5, else 1. - A's basis: draw
r;"+"ifr < 0.5, else"x". A prepares the qubit. - Draw
r; ifr < fraction, the spy intercepts: she draws her basis like step 2, measures the qubit in it, and replaces it by her result prepared in her basis. (This draw happens even whenfractionis 0 or 1.) - B's basis: drawn like step 2. B measures the qubit in it.
A position is sifted (kept) when A's and B's bases are equal; it is an error when it is sifted and B's bit differs from A's.
Write eavesdrop_run(n, fraction, seed) that returns (sifted, errors). Press Run with a loop over fraction and plot(fractions, [e / s for s, e in runs]) to see the error rate grow like fraction / 4.
Examples
Input: n = 8, fraction = 1, seed = 1
Output: (3, 1)
Input: n = 12, fraction = 1, seed = 3
Output: (7, 2)
Input: n = 1000, fraction = 0, seed = 5
Output: (501, 0)
Explanation: without the spy, a sifted position never has an error.
Constraints
0 <= n <= 20000,0 <= fraction <= 1
Goals
- Simulate BB84 with a seeded random generator, following a prescribed order of draws
- Measure a qubit in the + or x basis with the Born rule
- See that an eavesdropper who measures and resends leaves errors in the sifted key