Swap test circuit

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):

        [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

def SWAP_test1(A, B):
    qml.CSWAP(wires=[0, 1, 2])
    return qml.probs(wires=[0])

def SWAP_test2(A, B):
    qml.CSWAP(wires=[0, 1, 2])
    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(np.abs(compare - me1))
print(np.abs(compare - me2))


Yes, as you have already suspected, the reason for the difference is that you are using shots = 400, which generates a statistical sample of size 400. Measurement is probabilistic, so you will get an estimation of the probability from your sample, but this estimate need not be exact. If you want to check that the results are actually equal, you can remove the shots option! Doing this prioritizes analytical calculations. I have already tried this with your code, it’s working well!


1 Like