Python/quantum/q_fourier_transform.py

56 lines
1.9 KiB
Python
Raw Normal View History

import math
import numpy as np
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute
2024-10-08 18:02:43 +05:30
def quantum_fourier_transform(number_of_qubits: int = 3) -> dict:
"""
2024-10-08 18:02:43 +05:30
Build and simulate the Quantum Fourier Transform (QFT) circuit
for a given number of qubits using the Qiskit framework.
Args:
2024-10-08 18:02:43 +05:30
number_of_qubits (int): The number of qubits for the QFT circuit.
2024-10-08 18:02:43 +05:30
Returns:
dict: A dictionary containing the counts of measurement results.
Raises:
ValueError: If the number of qubits is less than or equal to 0,
greater than 10, or not an integer.
TypeError: If the input is not an integer.
"""
2024-10-08 18:02:43 +05:30
if not isinstance(number_of_qubits, int):
raise TypeError("Number of qubits must be an integer.")
if number_of_qubits <= 0:
2024-10-08 18:02:43 +05:30
raise ValueError("Number of qubits must be > 0.")
if number_of_qubits > 10:
2024-10-08 18:02:43 +05:30
raise ValueError("Number of qubits too large to simulate (>10).")
qr = QuantumRegister(number_of_qubits, "qr")
cr = ClassicalRegister(number_of_qubits, "cr")
quantum_circuit = QuantumCircuit(qr, cr)
2024-10-08 18:02:43 +05:30
# Apply the QFT circuit
for i in range(number_of_qubits):
quantum_circuit.h(i)
for j in range(i + 1, number_of_qubits):
quantum_circuit.cp(np.pi / 2 ** (j - i), j, i)
2024-10-08 18:02:43 +05:30
# Swap the qubits
for i in range(number_of_qubits // 2):
quantum_circuit.swap(i, number_of_qubits - i - 1)
2024-10-08 18:02:43 +05:30
# Measure all qubits
quantum_circuit.measure(qr, cr)
2024-10-08 18:02:43 +05:30
# Simulate the circuit with 10000 shots
backend = Aer.get_backend("qasm_simulator")
job = execute(quantum_circuit, backend, shots=10000)
2024-10-08 18:02:43 +05:30
result = job.result()
2024-10-08 18:02:43 +05:30
return result.get_counts(quantum_circuit)
if __name__ == "__main__":
2024-10-08 18:02:43 +05:30
result_counts = quantum_fourier_transform(3)
print(f"Total count for quantum fourier transform state is: {result_counts}")