Let be a state which can be efficiently generated, and let be a unitary gate. The Hadamard test produces a random variable whose image is in and whose expected value is exactly . A variant of the test produces a random variable whose expected value is .
To perform the Hadamard test we first calculate the state . We then apply the unitary operator on conditioned on the first qubit to obtain the state . We then apply the Hadamard gate to the first qubit, yielding .
Measuring the first qubit, the result is with probability , in which case we output . The result is with probability , in which case we output . The expected value of the output will then be the difference between the two probabilities, which is
To obtain a random variable whose expectation is follow exactly the same procedure but start with .