Let $\left|\psi \right\rangle$ be a state which can be efficiently generated, and let $U$ be a unitary gate. The Hadamard test produces a random variable whose image is in $\{\pm 1\}$ and whose expected value is exactly $\mathrm {Re} \left\langle \psi \mid U\mid \psi \right\rangle$ . A variant of the test produces a random variable whose expected value is $\mathrm {Im} \left\langle \psi \mid U\mid \psi \right\rangle$ .
To perform the Hadamard test we first calculate the state ${\frac {1}{\sqrt {2}}}\left(\left|0\right\rangle +\left|1\right\rangle \right)\otimes \left|\psi \right\rangle$ . We then apply the unitary operator on $\left|\psi \right\rangle$ conditioned on the first qubit to obtain the state ${\frac {1}{\sqrt {2}}}\left(\left|0\right\rangle \otimes \left|\psi \right\rangle +\left|1\right\rangle \otimes U\left|\psi \right\rangle \right)$ . We then apply the Hadamard gate to the first qubit, yielding ${\frac {1}{2}}\left(\left|0\right\rangle \otimes (I+U)\left|\psi \right\rangle +\left|1\right\rangle \otimes (I-U)\left|\psi \right\rangle \right)$ .
Measuring the first qubit, the result is $\left|0\right\rangle$ with probability ${\frac {1}{4}}\left\langle \psi \mid (I+U^{\dagger })(I+U)\mid \psi \right\rangle$ , in which case we output $1$ . The result is $\left|1\right\rangle$ with probability ${\frac {1}{4}}\left\langle \psi \mid (I-U^{\dagger })(I-U)\mid \psi \right\rangle$ , in which case we output $-1$ . The expected value of the output will then be the difference between the two probabilities, which is ${\frac {1}{2}}\left\langle \psi \mid (U^{\dagger }+U)\mid \psi \right\rangle =\mathrm {Re} \left\langle \psi \mid U\mid \psi \right\rangle$ To obtain a random variable whose expectation is $\mathrm {Im} \left\langle \psi \mid U\mid \psi \right\rangle$ follow exactly the same procedure but start with ${\frac {1}{\sqrt {2}}}\left(\left|0\right\rangle -i\left|1\right\rangle \right)\otimes \left|\psi \right\rangle$ .