smartyfy.mrindigi.com

Quantum Computing Master Course — 080. Fourier Algorithm Laboratory

Lesson 080: Fourier Algorithm Laboratory

Smartyfy Quantum Computing Master Course

Prerequisites and objectives

This laboratory checks Fourier transforms, exact phase readout, finite-precision distributions, and a tiny modular-order example in one local model. You will compare independently expressed formulas, preserve register ordering, and state which parts of the calculation are quantum-circuit predictions versus classical verification.

The code uses only Python’s standard library and was executed during lesson preparation. No quantum hardware, account, API key, or paid service is involved. Dense state vectors and matrices are deliberately used only at small dimensions where their behavior is easy to inspect.

Separate exact input data from numerical evaluation

Phase fractions such as five eighths and three tenths are stored as exact rational numbers. This avoids representing the problem’s specification with a rounded decimal before the calculation begins.

Complex exponentials and trigonometric functions are still evaluated in floating point. Their results are compared with tolerances, not described as exact symbolic arithmetic. Exact fractions establish which phase-grid cases should have probability one; numerical calculations verify the corresponding amplitudes approximately.

For N=4, many Fourier entries are exactly among 1,i,−1,−i divided by two, making hand calculations especially useful. For larger dimensions, retaining a clear algebraic target remains important even when the numerical entries involve irrational components.

Three complementary phase checks

First, transform a normalized complex vector and apply the inverse. The recovered vector should match the original, and squared norm should be preserved. Complex entries expose conjugation and sign errors that all-real examples can miss.

Second, use phase five eighths with three controls. The phase-ramp state is exactly F8|5⟩, so the inverse should produce integer five with probability one. Third, use phase three tenths and compare every probability against the geometric-sum formula from Lesson 077.

A round trip alone is not sufficient if both forward and inverse routines share a wrong convention. Comparing phase outputs and a separately expressed analytic distribution provides additional checks against such matched mistakes.

Executable standard-library calculation

All assertions in this program passed locally. The modular-power section constructs an ideal state directly; it does not synthesize reversible arithmetic gates or run a scalable factoring implementation.

from cmath import exp
from math import pi, sqrt, sin, gcd
from fractions import Fraction

TOL = 1e-11

def fourier(vector, inverse=False):
    size = len(vector)
    sign = -1 if inverse else 1
    return [sum(exp(sign*2j*pi*j*k/size)*vector[j] for j in range(size))/sqrt(size)
            for k in range(size)]

def phase_probabilities(phase, bits):
    size = 1 << bits
    ramp = [exp(2j*pi*float(k*phase))/sqrt(size) for k in range(size)]
    output = fourier(ramp, inverse=True)
    probabilities = [abs(z)**2 for z in output]
    assert abs(sum(probabilities)-1) < TOL
    for y, probability in enumerate(probabilities):
        delta = phase-Fraction(y, size)
        if delta.denominator == 1:
            expected = 1.0
        else:
            expected = sin(pi*size*float(delta))**2 / (size**2*sin(pi*float(delta))**2)
        assert abs(probability-expected) < TOL
    return probabilities

vector = [complex(k % 3 - 1, (2*k) % 5 - 2) for k in range(8)]
length = sqrt(sum(abs(z)**2 for z in vector))
vector = [z/length for z in vector]
transformed = fourier(vector)
recovered = fourier(transformed, inverse=True)
assert max(abs(a-b) for a, b in zip(vector, recovered)) < TOL
assert abs(sum(abs(z)**2 for z in transformed)-1) < TOL
exact = phase_probabilities(Fraction(5, 8), 3)
assert abs(exact[5]-1) < TOL
finite = phase_probabilities(Fraction(3, 10), 3)
print('QFT round trip and norm passed')
print('Exact phase 5/8: output', max(range(8), key=exact.__getitem__))
print('Phase 3/10 probabilities:', [round(p, 6) for p in finite])

# Explicit ideal modular-power state, not a compiled arithmetic circuit.
modulus, base, size = 15, 2, 16
joint = [[0j]*16 for _ in range(size)]
for k in range(size):
    joint[k][pow(base, k, modulus)] = 1/sqrt(size)
output = [[0j]*16 for _ in range(size)]
for z in range(16):
    column = fourier([joint[k][z] for k in range(size)], inverse=True)
    for y in range(size):
        output[y][z] = column[y]
probabilities = [sum(abs(z)**2 for z in row) for row in output]
assert all(abs(p-(0.25 if y in (0, 4, 8, 12) else 0)) < TOL
           for y, p in enumerate(probabilities))
order = next(r for r in range(1, modulus) if pow(base, r, modulus)==1)
x = pow(base, order//2, modulus)
factors = (gcd(x-1, modulus), gcd(x+1, modulus))
assert order == 4 and factors == (3, 5)
print('Order-finding nonzero probabilities:',
      {y: round(p, 6) for y, p in enumerate(probabilities) if p > TOL})
print('Classically verified toy order and factors:', order, factors)

Interpret the phase-estimation outputs

The exact phase test produces a peak at label five, interpreted as 5/8 because the control dimension is eight. The nonrepresentable phase produces the same eight-outcome distribution calculated in Lesson 077, including a nearest-label probability around 0.577521 at y=2.

The code already knows each test phase because it is generating a model with a specified eigenvalue. It is verifying the response of phase estimation, not discovering an unknown physical parameter through an experiment.

In a real algorithm, the phase dependence comes from controlled evolution of a target eigenstate. Replacing that evolution by a directly prepared phase ramp is a useful mathematical test but does not account for the cost or errors of implementing U and its powers.

The modular-power state

For base two modulo fifteen and control dimension sixteen, the ideal state after controlled modular powers is (1/4)Σk=0 to 15 |k⟩|2^k mod 15⟩. The target register has sixteen basis labels, although the orbit uses only residues one, two, four, and eight.

The code applies an inverse Fourier transform to the control amplitudes separately for every target label. This is the correct local-register action: target labels remain orthogonal and are not coherently merged.

When the target is unmeasured, the control probability is obtained by summing squared magnitudes over target labels. Adding those amplitudes before squaring would invent interference between distinct target states and give the wrong marginal.

Worked order-finding interpretation

Ideal control labels for base 2 modulo 15 with dimension 16
Label y Fraction y/16 Probability
0 0 1/4
4 1/4 1/4
8 1/2 1/4
12 3/4 1/4

Labels four and twelve display denominator four directly after reduction, while label eight displays denominator two and label zero is uninformative. The model therefore illustrates why one phase sample need not reveal the full order.

The final Python loop finds the tiny order by classical enumeration and checks the factors. This is an intentionally transparent validation step for N=15, not the efficient general classical postprocessing used by Shor’s algorithm. A scalable implementation uses phase accuracy, rational reconstruction, and modular verification rather than enumerating all possible orders.

The verified factors three and five multiply to fifteen. This arithmetic confirms the worked example but is not evidence of a practical quantum factoring advantage, since the entire model runs on a classical interpreter.

Design a useful test report

Record register dimensions, phase convention, initial state, transform direction, numerical tolerance, and expected support of each distribution. Distinguish a probability vector from any later sampled histogram. This program calculates probabilities directly and does not claim device shot counts.

If you add random sampling, each sampled physical trial would require a fresh preparation and circuit run. Reusing a computed classical distribution for many pseudorandom draws is a simulation shortcut, not an experimental reduction in controlled-evolution calls.

For the gate-level QFT itself, Lesson 074 already checked every matrix column through four qubits. This laboratory checks the Fourier algorithms’ higher-level state construction and marginal calculations. These layers complement one another rather than making either set of tests unnecessary.

Safe extensions

Try another exactly representable phase, then a fraction not aligned with the grid. Predict the nearest label and circular error before calculating the distribution. Check that the probability sum remains one and that the sine-ratio formula agrees with direct amplitude summation.

For modular examples, verify invertibility of the chosen base before treating multiplication as a residue permutation. Keep dimensions small and label any classical brute-force validation explicitly. Larger arrays consume exponentially more memory without becoming a scalable substitute for a quantum implementation.

Four exercises with worked solutions

  1. For phase 7/16 and four controls, predict the exact output.

    Solution. The phase ramp is F16|7⟩, so the inverse produces label seven, or bit string 0111, with probability one in the ideal model.

  2. Why is the modular joint array sixteen by sixteen?

    Solution. There are sixteen control labels and sixteen target basis labels. The full eight-qubit state therefore contains 256 amplitudes, even though many are initially zero.

  3. Why does y=8 not immediately establish order two?

    Solution. Its fraction is 1/2, which can be a reduced form of s/r=2/4. Candidate verification rejects two because 2² modulo fifteen is four, not one.

  4. What does exact Fraction storage guarantee, and what does it not?

    Solution. It preserves the specified rational phase exactly and identifies exact grid alignment. It does not make the subsequent transcendental complex arithmetic exact; those calculations still use floating-point tolerances.

Five explained multiple-choice questions

  1. The phase-ramp test verifies: A. Every possible noise channel. B. A controlled-evolution response model for a known test phase. C. An unknown hardware phase measurement. D. A full fault-tolerant implementation.

    Answer: B. The phase is supplied to construct the ideal mathematical test.

  2. Target labels are removed from a control marginal by: A. Adding all amplitudes first. B. Choosing the largest label. C. Summing squared magnitudes over them. D. Replacing them with equal phases.

    Answer: C. Orthogonal target alternatives contribute incoherent probabilities to the marginal.

  3. The classical order-enumeration loop is: A. Quantum hardware execution. B. Free for arbitrarily large N. C. Shor’s general efficient postprocessor. D. A tiny-example validation method.

    Answer: D. It is explicitly not the scalable order-reconstruction procedure.

  4. Round-trip agreement alone can miss: A. A mismatch between the forward and inverse register sizes. B. Every normalization error necessarily. C. A shared wrong convention in both transforms. D. All output dimensions.

    Answer: C. Independent expected-output checks help catch matched implementation mistakes.

  5. The results demonstrate: A. Consistency of the specified ideal calculations and toy arithmetic. B. A measured quantum speedup. C. That factors were found by physical qubits. D. That modular arithmetic has zero cost.

    Answer: A. The scope is local classical verification of a quantum mathematical model.

Pitfalls and summary

Keep exact problem data, numerical amplitudes, classical validation, and physical execution distinct. Verify Fourier signs and target marginals independently. The small laboratory connects the phase and order-finding derivations without disguising state preparation or arithmetic as free resources.

Primary sources and further study

These sources support the definitions and context. The numerical examples, exercises, and explanations here were prepared for this lesson. Research papers are optional advanced reading.