Skip to main content

05 - Grover's Algorithm: Quantum Search

Grover finds one element out of N in about the square root of N steps, but with too many steps the probability collapses: you simulate and check it in NumPy.

What do you think about this article?

05 - Grover's Algorithm: Quantum Search
Quantum Computingfedericocalo.dev

At a Glance

Grover finds one element out of N in about the square root of N steps, but with too many steps the probability collapses: you simulate and check it in NumPy.

You have a list of $N$ elements with no order at all and a way to recognize the right one when you look at it. A classical program can only look: on average it finds it after about $N/2$ attempts, and no classical algorithm, not even a probabilistic one, does better than $N/2$ attempts to get a 50% probability, as Grover states in the abstract of his 1996 paper. Grover's algorithm finds it with about $\tfrac{\pi}{4}\sqrt N$ queries: for $N = 1024$ that is 25 steps, with success probability 0.9995. What surprises those who meet it for the first time is that the number of steps is critical. If you do 50 instead of 25, the probability of finding the element drops to 0.0002.

This is the fifth lesson of Quantum Computing in Italiano. You need the superposition and interference from the first lesson and the idea of an oracle from the fourth. The listing is NumPy (Python 3.14.4, NumPy 2.5.4), in local simulation; I repeated the result with the Grover operator of Qiskit 2.6.2.

Two reflections that rotate the state

The algorithm starts from the uniform superposition, with amplitude $1/\sqrt N$ on every element. Then it repeats two operations. The first is the oracle: it flips the sign of the amplitude of the sought elements and leaves the others alone. The second is the diffusion: it reflects every amplitude about the mean of all of them, that is it replaces $a_x$ (where $\mu$ is the mean) with $2\mu - a_x$. An example with numbers: if all the amplitudes are 0.5 and the oracle flips one to −0.5, the mean is 0.25, the diffusion takes the flipped amplitude to $2 \cdot 0.25 + 0.5 = 1$ and the others to 0. With $N = 4$ one step is enough.

Seen geometrically, the state always lies in the plane spanned by two vectors, the superposition of the sought elements and that of the others. The Grover step, two reflections in sequence, is a rotation by an angle $2\theta$ in that plane, with $\sin\theta = \sqrt{M/N}$ if there are $M$ sought elements. After $k$ steps the probability of measuring a sought element is $\sin^2((2k+1)\theta)$: this is the closed formula that Boyer, Brassard, Høyer and Tapp derive in their paper (their abstract announces it).

import numpy as np

def grover(n, marked, iterations):
    """Returns the probability of measuring a marked element after 0..iterations steps."""
    N = 2 ** n
    a = np.full(N, 1 / np.sqrt(N))              # H^n |0...0>: equal amplitudes
    marked = list(marked)
    p = [float((a[marked] ** 2).sum())]
    for _ in range(iterations):
        a[marked] *= -1                         # oracle: flips the sign of the sought elements
        a = 2 * a.mean() - a                    # diffusion: reflection about the mean
        p.append(float((a[marked] ** 2).sum()))
    return np.array(p)

def formula(N, M, k):
    theta = np.arcsin(np.sqrt(M / N))
    return np.sin((2 * k + 1) * theta) ** 2

# N = 4, a single sought element: one iteration is enough
print("N=4, M=1:", np.round(grover(2, [3], 3), 6))

# N = 1024, one element: simulation against the formula sin^2((2k+1) theta)
n, N, M = 10, 1024, 1
p = grover(n, [700], 60)
ks = np.arange(61)
print("maximum gap simulation/formula over k=0..60 below 1e-12:", float(np.abs(p - formula(N, M, ks)).max()) < 1e-12)
theta = np.arcsin(np.sqrt(M / N))
k_opt = int(np.floor(np.pi / (4 * theta)))
print("optimal k:", k_opt, " pi/4*sqrt(N) =", round(np.pi / 4 * np.sqrt(N), 2))
for k in (0, 1, 5, 10, 20, k_opt, k_opt + 5, 40, 50, 60):
    print(f"  k={k:2d}  P={p[k]:.4f}")

# Four sought elements out of 1024: you get there sooner, and beyond that you lose
M = 4
p4 = grover(n, [3, 77, 500, 900], 40)
k4 = int(np.floor(np.pi / (4 * np.arcsin(np.sqrt(M / N)))))
print("M=4: optimal k", k4, " P =", round(p4[k4], 4), " P at k=2*k_opt:", round(p4[2 * k4], 4))
print("M=4 but with k=25, the optimum for M=1: P =", round(p4[25], 4))

# optimal k and comparison with classical search without repetitions
print("    n          N  optimal k  P(success)  expected classical queries (N+1)/2")
for n in (4, 8, 12, 16):
    N = 2 ** n
    th = np.arcsin(np.sqrt(1 / N))
    k = int(np.floor(np.pi / (4 * th)))
    ps = grover(n, [N // 3], k + 3)
    assert int(np.argmax(ps)) == k            # the simulated maximum falls exactly at k
    print(f"{n:5d} {N:10d} {k:10d}  {ps[k]:10.6f}  {(N + 1) / 2:12.1f}")

# Output:
# N=4, M=1: [0.25 1.   0.25 0.25]
# maximum gap simulation/formula over k=0..60 below 1e-12: True
# optimal k: 25  pi/4*sqrt(N) = 25.13
#   k= 0  P=0.0010
#   k= 1  P=0.0088
#   k= 5  P=0.1136
#   k=10  P=0.3724
#   k=20  P=0.9186
#   k=25  P=0.9995
#   k=30  P=0.8914
#   k=40  P=0.3281
#   k=50  P=0.0002
#   k=60  P=0.3569
# M=4: optimal k 12  P = 0.9999  P at k=2*k_opt: 0.0059
# M=4 but with k=25, the optimum for M=1: P = 0.0023
#     n          N  optimal k  P(success)  expected classical queries (N+1)/2
#     4         16          3    0.961319           8.5
#     8        256         12    0.999947         128.5
#    12       4096         50    0.999945        2048.5
#    16      65536        201    0.999988       32768.5

The listing has two functions, grover and formula; grover keeps only the vector of amplitudes a. The line a[marked] *= -1 is the oracle, the line a = 2 * a.mean() - a is the diffusion. The comparison with the formula $\sin^2((2k+1)\theta)$ over $k = 0, \dots, 60$ for $N = 1024$ gives gaps below $10^{-12}$, so the formula describes the simulation down to numerical precision. The case $N = 4$ prints [0.25 1. 0.25 0.25]: after one step the probability is exactly 1, after two it returns to 0.25.

The table for $N = 1024$ with one sought element reads like this: $\theta \approx 0.0313$ rad, so the rotation reaches almost 90° (maximum probability) after k = floor(pi/(4*theta)) = 25 steps, and $\tfrac{\pi}{4}\sqrt N$ is 25.13. The probability is 0.9186 at $k = 20$, 0.9995 at $k = 25$ and 0.8914 at $k = 30$. Beyond that, the state keeps rotating and goes past the target: 0.3281 at $k = 40$, 0.0002 at $k = 50$, and again 0.3569 at $k = 60$. The first thing to do when a Grover result seems wrong is to count the steps.

More solutions, and the problem of not knowing how many

With $M = 4$ sought elements out of 1024, $\theta$ is doubled and the optimal number drops to 12 steps, with probability 0.9999. The listing also shows how to get it wrong: at 24 steps (double) the probability is 0.0059, and if you use the optimal number for a single element ($k = 25$) when in fact there are four, it drops to 0.0023. In practice $M$ is often unknown. Boyer and colleagues propose, according to their abstract, a new algorithm that works even when the number of solutions is not known in advance, and a technique for approximate counting. I have not read the details and I do not report them here.

How much the saving is worth

The last part of the listing computes, for $n = 4, 8, 12, 16$ qubits, the optimal number of steps and compares it with classical search without repetitions, which on average queries $(N+1)/2$ elements if the sought element is at a uniformly random position. The instruction assert int(np.argmax(ps)) == k checks that the maximum of the simulated probability falls exactly at $k$.

$n$$N$Grover stepsprobabilityclassical, expected queries
41630.96138.5
8256120.9999128.5
124,096500.99992,048.5
1665,5362011.000032,768.5

The table reports the values of the output: the gain grows with $N$, from about 3 times at $n = 4$ to about 163 times at $n = 16$ (32,768.5 divided by 201), but it is a quadratic gain, not an exponential one: for every two qubits added, $N$ is multiplied by 4, the expected classical queries are multiplied by 4 and the Grover steps only by 2. At 4 qubits the probability is 0.9613 and not 1: with $N = 16$ the rotation does not land exactly on 90°.

The saving is real only in one precise count: the calls to the oracle. In the simulation the oracle is a list of indices that the program already knows, so building it costs $N$ classical checks and the simulation is no faster than a classical search. On a device, the oracle is a circuit that evaluates the recognition criterion on all the positions in superposition, and its cost in gates enters the total cost. The limit is technical, and holds for any use: the problem must have a verification criterion that can be turned into a circuit.

That the quadratic saving cannot be improved much, in the oracle model, is a lower-bound result. According to the abstract of Boyer and colleagues, Grover's algorithm is within a factor of 2 of the optimum in number of queries. The abstract of Bennett, Bernstein, Brassard and Vazirani shows that, relative to a randomly chosen oracle, the class NP cannot be solved on a quantum Turing machine in time $o(2^{n/2})$, and observes that the bound is tight because Grover reaches it. Translated: according to these results, a quantum computer that uses the oracle as a black box cannot search exponentially faster. I read only the abstracts in full; I cannot say anything about the cases in which the problem has a structure to exploit.

The mistakes made most often

  • Counting the steps wrong: stopping too late, like at 50 steps for $N = 1024$, wipes out the success.
  • Using the number of steps for a single element when there is more than one solution, or vice versa, without knowing how many there are.
  • Presenting Grover as "it tries all the answers together": one measurement yields a single element, and the advantage comes from interference that moves amplitude toward the right one.
  • Counting the cost in queries and forgetting that of the oracle or of the hardware it runs on.

The four mistakes lead to opposite conclusions: the first two make the algorithm fail, the last two make you say it works better than it is worth. In any case the check is the same: compare the probability with the formula $\sin^2((2k+1)\theta)$ before trusting any other figure.

What you can do now

You can write Grover's algorithm in ten lines of NumPy, explain the step as a rotation by an angle $2\theta$, compute the optimal number of steps for $M$ solutions and predict how far the probability falls if you get it wrong. You can say in which unit the saving is measured, the oracle calls, and why it holds against probabilistic classical algorithms, unlike Deutsch-Jozsa. The next lesson takes up the case in which the structure of the problem allows a much larger advantage: factoring.

Frequently asked questions

How many iterations does Grover's algorithm need?

About $\tfrac{\pi}{4}\sqrt{N/M}$ for $M$ sought elements: 25 for $N = 1024$ and a single element, 12 with four. The success probability after $k$ steps is $\sin^2((2k+1)\theta)$ with $\sin\theta = \sqrt{M/N}$.

What happens if I do too many iterations?

The probability drops, because the state keeps rotating past the target. For $N = 1024$ it is 0.9995 at 25 steps, 0.3281 at 40 and 0.0002 at 50.

Is Grover exponentially faster than a classical search?

No, it is quadratic: about $\sqrt N$ queries against about $N/2$. At 16 qubits that is 201 steps against 32,768.5 expected queries. According to the abstracts cited, no quantum algorithm that uses the oracle as a black box does much better.

Does the advantage hold against probabilistic algorithms too?

Yes: Grover's abstract says that every classical algorithm, deterministic or probabilistic, must look at at least $N/2$ elements to have a 50% probability of success.

Later in the series you will also find QAOA (article 8).

Sources

The listing was run twice with Python 3.14.4 and NumPy 2.5.4, with identical output. With Qiskit 2.6.2 (GroverOperator, $n = 4$, one marked element) the probabilities for $k = 0, \dots, 6$ are 0.0625, 0.4727, 0.9084, 0.9613, 0.5817, 0.1255 and 0.0204; the value at $k = 3$ coincides with that of the listing (0.9613). Of the three arXiv sources I read only the abstract; titles, authors and dates I checked on the arXiv API.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects