Measure $\langle \hat{X}\rangle$ and $\langle \hat{Y}\rangle$ from counts

I'm confused about how I can measure $$\langle \hat{X}\rangle$$ and $$\langle \hat{Y}\rangle$$ using counts. Here's my code for X:

x-basis:

# Measurement in x-basis.
quanc_x = QuantumCircuit(1)
quanc_x.u(1,2,3,0) # prepare some random state
quanc_x.h(0)
quanc_x.measure_all()
quanc_x.draw(output='mpl')

# number of repetitions
N = 10000

backend = Aer.get_backend( 'qasm_simulator' )
job = execute( quanc_x, backend, shots=N )
result = job.result()

measurement_result = result.get_counts( quanc_x )
print( measurement_result )
plot_histogram( measurement_result )

cos_phi_est = ( measurement_result['0'] - measurement_result['1'] ) / N  #<--Question
print( "cos(phi) estimated: ", cos_phi_est )


My question of this code is marked above. I'm not pretty sure if that looks correct. For Pauli X, we have $$\langle \hat{X}\rangle=\langle\psi|0\rangle\langle1|\psi\rangle+\langle\psi|1\rangle\langle0|\psi\rangle$$ Can I simplify that further? Should that correspond to my code with the question mark? How can I apply that to $$\langle \hat{Y}\rangle$$? Thanks for the help!

That looks right to me.

Since, $$HZH = X$$ then we have that $$\langle \psi | X | \psi \rangle = \langle \psi | HZH | \psi \rangle = \langle \psi H | Z | H\psi \rangle$$.

In your code, you generate $$|\psi \rangle$$ with a $$U_3(\theta, \phi, \lambda)$$ gate applied to $$|0\rangle$$. Then you applied the Hadamard gate ($$H$$) before measuring which is what needed to measure in the $$X$$ basis as discussed above.

For $$\langle Y \rangle$$ you should note that $$(SH)Z(HS^\dagger) = Y$$

$$\langle \psi |Y| \psi \rangle = \langle \psi | (SH)Z (HS^\dagger) | \psi \rangle = \langle \psi SH | Z | H S^\dagger \psi \rangle$$

Thus, here you want to apply $$S^\dagger$$ follow by the Hadamard gate $$H$$ before measurement.

• Thanks for the answer! If I want to find the expectation value from counts, is my code also correct for $X$? (( measurement_result['0'] - measurement_result['1'] ) / N)Should that be the same as $Y$?
– ZR-
Jul 30 at 23:25
• Yes. The counts remain the same as you wrote it. Jul 30 at 23:28
• Thanks, can I understand the measured expectation value as the difference of some probabilities? Why it is not result[1]- result[0]?
– ZR-
Jul 30 at 23:31
• You already rotate to the computational basis once you apply the rotation $H$ or $H S^\dagger$ to your state $|\psi \rangle$. In the $Z$ basis, $|0\rangle$ has eigenvalue of $+1$ and $|1\rangle$ has eigenvalue of $-1$ since $Z|0\rangle = 1|0\rangle$ and $Z|1\rangle = -1 |1\rangle$. Jul 30 at 23:42