1

Background

In 2022 Qiskit released a very nice tutorial detailing how the expectation value of an operator could be found using CircuitOp. As of 2024, these techniques (and others that I have found on the quantum computing stack exchange) are unusable as they are deprecated. The migration guide suggests using Estimators. As a test, I tried writing some code to calculate the exact (non-simulated) expected value of $\langle0|H|0\rangle$ which, I believe, should be equal to $\dfrac{1}{\sqrt{2}}$. Instead, I got $0.9999999999999999$. I include my code below (as it is quite short).

The Code

from qiskit import QuantumCircuit
from qiskit.primitives import Estimator

testCircuit = QuantumCircuit(1) testCircuit.h(0)

estimator = Estimator()

result = estimator.run(testCircuit, 'I').result() print(result.values[0])

The Question

What is the best practice (in 2024) for calculating the exact expected value of any observable specified as a matrix and/or circuit using Qiskit?

FDGod
  • 2,278
  • 2
  • 4
  • 29
Shadow43375
  • 197
  • 4

1 Answers1

1

This is how you do it with the latest Qiskit Packages:

Step 1: Expectation Value of an Operator

$$E = \langle \psi |O|\psi\rangle$$

Make the circuit you want to measure the $\psi$ with

from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister

circuit = QuantumCircuit(2) circuit.x(0) circuit.x(1) #op = CircuitOp(circuit) circuit.draw(style='iqx',output='mpl')

Step 2: The Operator

Make the operator you want to measure the expectation value of:


from qiskit.quantum_info import Pauli, SparsePauliOp

X = Pauli('X') Y = Pauli('Y') Z = Pauli('Z') I = Pauli('I') operator = SparsePauliOp(["II", "IZ", "ZI","ZZ","XX" ], coeffs = [-1.052373245772859, 0.39793742484318045,-0.39793742484318045, -0.01128010425623538,0.18093119978423156 ]) #op = (-1.052373245772859 * I^I) + (0.39793742484318045 * I^Z) +

(-0.39793742484318045 * Z^I) + (-0.01128010425623538 * Z^Z) +

#(0.18093119978423156 * X^X)

print(operator)

Step 3: The State

The state you want to measure against:

from qiskit.quantum_info import SparsePauliOp, Statevector
from qiskit.primitives import Estimator
psi = QuantumCircuit(2)
psi.x(0)
psi.x(1)
estimator = Estimator()
#psi = Statevector(psi)
expectation_value = estimator.run(psi, operator).result().values.real

The result

print(expectation_value)

This follows the youtube tutorial you linked, but with the latest qiskit packages, you can change as per you need.

  • Thank you for the response. Is there an easy way to create an Operator directly from a QuantumCircuit? For my current workflow that would make a lot more sense. – Shadow43375 Feb 04 '24 at 11:14
  • Check out this answer : https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit?noredirect=1&lq=1 – Yet another Random Guy Feb 19 '24 at 07:38