1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

量子コンピューティングのPytnonのサンプルコード

Posted at

量子コンピューティングのPytnonのサンプルコードを、生成AIの Claude Opus 4 に示してもらった。
即座にこの4つのコードを示してきたので、内心、圧倒された。

回答

量子コンピューティングの基本概念を理解するための簡単なPythonプログラムを紹介します。

1. 最もシンプルな例:量子コイン投げ

# 量子コンピューティング入門:量子コイン投げ
# 必要なライブラリ:pip install qiskit matplotlib

from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt

# 量子回路を作成(1量子ビット、1古典ビット)
qc = QuantumCircuit(1, 1)

# アダマールゲートで重ね合わせ状態を作る
# |0⟩ → (|0⟩ + |1⟩)/√2
qc.h(0)

# 量子ビットを測定
qc.measure(0, 0)

# 回路を表示
print("量子回路:")
print(qc.draw())

# シミュレーターで実行
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=1000)
result = job.result()
counts = result.get_counts(qc)

# 結果を表示
print("\n測定結果(1000回):")
print(counts)

# ヒストグラムで可視化
plot_histogram(counts)
plt.title("量子コイン投げの結果")
plt.show()

2. 量子の重ね合わせを視覚化

# 量子状態の重ね合わせを段階的に見る

from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_bloch_multivector
from math import pi
import matplotlib.pyplot as plt

# 異なる角度で回転させた量子状態を作る
angles = [0, pi/4, pi/2, 3*pi/4, pi]
fig, axes = plt.subplots(1, 5, figsize=(20, 4))

for i, theta in enumerate(angles):
    # 新しい回路を作成
    qc = QuantumCircuit(1)
    
    # Y軸周りに回転(重ね合わせの度合いを調整)
    qc.ry(theta, 0)
    
    # 状態ベクトルを取得
    backend = Aer.get_backend('statevector_simulator')
    job = execute(qc, backend)
    state = job.result().get_statevector()
    
    # ブロッホ球に表示
    plot_bloch_multivector(state, ax=axes[i])
    axes[i].set_title(f'θ = {theta:.2f}')

plt.suptitle('量子ビットの重ね合わせ状態の変化')
plt.tight_layout()
plt.show()

3. 量子もつれ(エンタングルメント)のデモ

# 量子もつれ:2つの量子ビットの不思議な相関

from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt

# ベル状態を作る関数
def create_bell_pair():
    qc = QuantumCircuit(2, 2)
    
    # 量子ビット0を重ね合わせ状態に
    qc.h(0)
    
    # CNOTでもつれ状態を作る
    qc.cx(0, 1)
    
    # 両方の量子ビットを測定
    qc.measure([0, 1], [0, 1])
    
    return qc

# 通常の(もつれていない)2ビット
def create_independent_qubits():
    qc = QuantumCircuit(2, 2)
    
    # 両方の量子ビットを独立に重ね合わせ
    qc.h(0)
    qc.h(1)
    
    # 測定
    qc.measure([0, 1], [0, 1])
    
    return qc

# 両方の回路を実行
simulator = Aer.get_backend('qasm_simulator')

# もつれた量子ビット
bell_qc = create_bell_pair()
bell_job = execute(bell_qc, simulator, shots=1000)
bell_counts = bell_job.result().get_counts()

# 独立した量子ビット
indep_qc = create_independent_qubits()
indep_job = execute(indep_qc, simulator, shots=1000)
indep_counts = indep_job.result().get_counts()

# 結果を比較
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

plot_histogram(bell_counts, ax=ax1)
ax1.set_title("もつれた量子ビット\n(00と11のみ出現)")

plot_histogram(indep_counts, ax=ax2)
ax2.set_title("独立した量子ビット\n(00, 01, 10, 11すべて出現)")

plt.tight_layout()
plt.show()

print("ベル状態(もつれ)の測定結果:")
print(bell_counts)
print("\n独立した量子ビットの測定結果:")
print(indep_counts)

4. 量子アルゴリズムの簡単な例:Deutschのアルゴリズム

# Deutschのアルゴリズム:関数が定数か平衡かを1回で判定

from qiskit import QuantumCircuit, Aer, execute
import numpy as np

def deutsch_algorithm(oracle_type='balanced'):
    """
    oracle_type: 'constant_0', 'constant_1', 'balanced_id', 'balanced_not'
    """
    qc = QuantumCircuit(2, 1)
    
    # 初期化:|01⟩
    qc.x(1)
    
    # アダマールゲートで重ね合わせ
    qc.h(0)
    qc.h(1)
    
    # オラクル(ブラックボックス関数)
    if oracle_type == 'constant_0':
        # f(x) = 0(何もしない)
        pass
    elif oracle_type == 'constant_1':
        # f(x) = 1
        qc.x(1)
    elif oracle_type == 'balanced_id':
        # f(x) = x
        qc.cx(0, 1)
    elif oracle_type == 'balanced_not':
        # f(x) = NOT x
        qc.x(0)
        qc.cx(0, 1)
        qc.x(0)
    
    # アダマールゲート
    qc.h(0)
    
    # 測定
    qc.measure(0, 0)
    
    return qc

# 各タイプのオラクルを試す
oracle_types = ['constant_0', 'constant_1', 'balanced_id', 'balanced_not']
results = {}

simulator = Aer.get_backend('qasm_simulator')

for oracle in oracle_types:
    qc = deutsch_algorithm(oracle)
    job = execute(qc, simulator, shots=100)
    counts = job.result().get_counts()
    results[oracle] = counts

# 結果を表示
print("Deutschのアルゴリズムの結果:")
print("-" * 40)
for oracle, counts in results.items():
    if '0' in counts and counts.get('0', 0) == 100:
        function_type = "定数関数"
    else:
        function_type = "平衡関数"
    print(f"{oracle:15}{function_type} (測定結果: {counts}")

実行方法

  1. Qiskitをインストール:
pip install qiskit matplotlib
  1. 上記のコードをPythonファイルに保存して実行

学習のポイント

  1. 重ね合わせ(Superposition):量子ビットは0と1の両方の状態を同時に持てる
  2. もつれ(Entanglement):複数の量子ビットが相関を持つ特殊な状態
  3. 測定(Measurement):観測すると重ね合わせが崩壊し、確率的に0か1になる
  4. 量子ゲート:量子状態を操作する基本演算

これらのプログラムを順番に実行することで、量子コンピューティングの基本概念を体験的に理解できます。

以上 Claude の回答

 量子の重ね合わせが帰巣本能に使われている可能性や、量子のもつれが嗅覚感知や天才的ひらめきや武道の反応に使われている可能性が唱えられている。このようなアルゴリズム的アプローチは今日的な題材だ。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?