从DFT到QFT:如何将给定经典DFT代码转为量子版本(Python/Qiskit)
Great question! Converting your classic DFT code to a quantum implementation means building the Quantum Fourier Transform (QFT)—the quantum analog of the DFT that leverages quantum parallelism for exponential speedups on large datasets. Let’s walk through how to do this with Qiskit, Python’s go-to framework for quantum computing.
First, let’s recap your original classical DFT code for reference:
import numpy as np x = [1, -4, 5, -2] # Data points N = len(x) # Number of samples n = np.arange(N) # Current sample k = n.reshape((N, 1)) # Current frequency e = np.exp(-2j * np.pi * k * n / N) # Exponential part DFT = np.dot(e, x)
This computes a 4-point DFT, which maps cleanly to a 2-qubit quantum circuit (since quantum states live in a 2ⁿ-dimensional space, where n is the number of qubits—here 2 qubits give us 4 states, matching your 4 samples).
Key Differences Between Classical DFT and Quantum QFT
- Classical DFT operates on classical vectors, while QFT acts on quantum superpositions.
- QFT uses O(n²) quantum gates (for n qubits) instead of the O(N²) classical operations (for N=2ⁿ samples), making it exponentially faster for large N.
- Quantum states require normalized amplitudes, so we’ll need to adjust your input first.
Step-by-Step Quantum Implementation
1. Set Up Dependencies
First, install Qiskit if you haven’t, then import the required modules:
import numpy as np from qiskit import QuantumCircuit, Aer, execute from qiskit.circuit.library import QFT from qiskit.visualization import plot_histogram
2. Prepare and Normalize Input Data
Quantum state amplitudes must sum to 1 in magnitude squared, so we’ll normalize your input vector:
# Original classical input x = np.array([1, -4, 5, -2], dtype=np.complex128) N = len(x) # Normalize the vector to meet quantum state requirements norm_factor = np.linalg.norm(x) x_normalized = x / norm_factor
3. Build the Quantum Circuit
We’ll create a circuit that:
- Loads the normalized input into a quantum state.
- Applies the QFT.
- Measures the qubits to retrieve frequency-domain results.
# Create a circuit with 2 qubits (for 4 states) and 2 classical bits for measurement qc = QuantumCircuit(2, 2) # Load the normalized input as quantum state amplitudes qc.initialize(x_normalized, qubits=[0, 1]) # Append the QFT circuit (do_swaps=True ensures output matches classical DFT indexing) qc.append(QFT(num_qubits=2, do_swaps=True), qubits=[0, 1]) # Measure qubits to classical bits qc.measure(qubits=[0, 1], clbits=[0, 1]) # Optional: Visualize the circuit qc.draw(output='mpl')
4. Run the Simulation
We’ll use Qiskit’s Aer simulator to run the circuit. We have two options:
Option A: Sampling (Probabilistic Results)
This mimics a real quantum computer, where we get counts of measurement outcomes:
# Use the QASM simulator (for sampling) simulator = Aer.get_backend('qasm_simulator') result = execute(qc, simulator, shots=1024).result() measurement_counts = result.get_counts() # Plot the measurement results plot_histogram(measurement_counts)
The binary keys (e.g., '00', '01') correspond to frequency indices k=0, k=1, etc. The counts reflect the probability of measuring each frequency state, which is proportional to the squared magnitude of the classical DFT value.
Option B: State Vector Simulation (Exact Amplitudes)
For precise results (no sampling noise), use the state vector simulator:
# Remove measurements first to get the full state vector qc_no_measure = qc.remove_final_measurements() # Use the state vector simulator state_sim = Aer.get_backend('statevector_simulator') state_result = execute(qc_no_measure, state_sim).result() state_vector = state_result.get_statevector() # Scale back by the normalization factor to match classical DFT values quantum_dft_exact = state_vector * norm_factor
5. Compare Quantum and Classical Results
Let’s verify that the quantum output matches your original classical DFT:
# Compute classical DFT for comparison n = np.arange(N) k = n.reshape((N, 1)) exp_matrix = np.exp(-2j * np.pi * k * n / N) classical_dft = np.dot(exp_matrix, x) print("Classical DFT Results:\n", classical_dft) print("\nExact Quantum DFT Results:\n", quantum_dft_exact)
You’ll see the results are nearly identical (small differences are due to floating-point precision).
Key Takeaways
- Input Encoding: Classical data is converted to quantum state amplitudes (requires normalization).
- QFT Equivalence: The QFT computes the same mathematical transform as the classical DFT, but in a quantum state.
- Measurement vs State Vector: Sampling gives probabilistic results (like real hardware), while state vector simulation gives exact amplitudes for testing.
内容的提问来源于stack exchange,提问作者Steve Bermeo

