I want to perform the swap test in order to compute the inner product between two states/vector A,B
. It appears the both of the state preparation methods I tried give results that disagree with np.dot(A,B)
. Sometimes, though, the results are close, is it only because of the probabilistic nature of the computation?
inner_dev = qml.device("default.mixed", wires=[0, 1, 2], shots=400)
def SWAP_prep1(A, B):
qml.AmplitudeEmbedding(
[A[0] * B[0], A[0] * B[1], A[1] * B[0], A[1] * B[1]], wires=[1, 2], normalize=True)
return 0
def SWAP_prep2(A, B):
phi_a = np.arctan(A[0] / A[1]) if A[1] != 0 else 0
phi_b = np.arctan(B[0] / B[1]) if B[1] != 0 else 0
qml.RY(2 * (np.pi/2 - phi_a), wires=1)
qml.RY(2 * (np.pi/2 - phi_b), wires=2)
return 0
@qml.qnode(inner_dev)
def SWAP_test1(A, B):
SWAP_prep1(A,B)
qml.Hadamard(0)
qml.CSWAP(wires=[0, 1, 2])
qml.Hadamard(0)
return qml.probs(wires=[0])
@qml.qnode(inner_dev)
def SWAP_test2(A, B):
SWAP_prep2(A,B)
qml.Hadamard(0)
qml.CSWAP(wires=[0, 1, 2])
qml.Hadamard(0)
return qml.probs(wires=[0])
def inner_swap(A,B):
inner_product1 = SWAP_test1(A, B)[0]
prod1 = (2 * inner_product1 - 1)**0.5
inner_product2 = SWAP_test2(A, B)[0]
prod2 = (2 * inner_product2 - 1)**0.5
return np.round(prod1,5), np.round(prod2,5)
v = np.random.random(2)
v = v / np.linalg.norm(v)
u = np.random.random(2)
u = u / np.linalg.norm(u)
me1, me2 = inner_swap(u,v)
print(me1)
print(me2)
print(compare)
print(np.abs(compare - me1))
print(np.abs(compare - me2))