Skip to content

Instantly share code, notes, and snippets.

@smrfeld
Created July 25, 2020 05:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smrfeld/512ccf946833cdfa66c77f9affc708b7 to your computer and use it in GitHub Desktop.
Save smrfeld/512ccf946833cdfa66c77f9affc708b7 to your computer and use it in GitHub Desktop.
Test for Grover algorithm
import math
import basis_vector as bv
import state as s
import state_pair as sp
import operators as op
# Length
N = 100
# k0
k0 = 1
k0_pair_list = [sp.State_Pair.createFromSingleBasisVector(
name=str(k0),
basis=1,
coefficient=1
)]
k0_state = s.State(k0_pair_list)
print("Created k0 state: %s" % k0_state)
# Phi
# Basis has index 1
phi_pair_list = []
for i in range(0,N):
phi_pair_list.append(sp.State_Pair.createFromSingleBasisVector(
name=str(i),
basis=1,
coefficient=1./math.sqrt(N)
))
phi = s.State(phi_pair_list)
print("Created phi state: %s" % phi)
# Yes/no states
# Basis has index 2
yn_pair_list = []
yn_pair_list.append(sp.State_Pair.createFromSingleBasisVector(
name="yes",
basis=2,
coefficient=-1.0/math.sqrt(2)
))
yn_pair_list.append(sp.State_Pair.createFromSingleBasisVector(
name="no",
basis=2,
coefficient=1.0/math.sqrt(2)
))
yn_state = s.State(yn_pair_list)
print("Created yn state: %s" % yn_state)
# Phi full
phi_full = phi*yn_state
print("Created phi full state: %s" % phi_full)
# Initial observation:
print("-----------------------------------------------------")
print("Probability of observing k0 for N = %d" % N)
print("-----------------------------------------------------")
print("Step | Probability | Comparison with step number / N")
print("-----------------------------------------------------")
prob = (yn_state*k0_state*phi_full)*(yn_state*k0_state*phi_full)
print("%04d | %s | %f" % (0, prob, 1.0/N))
# Iterate
max_obs = math.sqrt(N)*math.pi/4.
i=1
while i<max_obs:
V_phi = op.operatorV(phi_full,str(k0))
W_V_phi = op.operatorW(V_phi,phi)
W_V_phi = W_V_phi.int_prod(-1)
phi_full = W_V_phi
# Log
prob = (yn_state*k0_state*phi_full)*(yn_state*k0_state*phi_full)
print("%04d | %s | %f" % (i, prob, (i+1.0)/N))
# Next
i = i+1
print("-----------------------------------------------------")
print("Final step probability > 1-1/N = %f" % (1.0-1.0/N))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment