Hi!

I’m trying to implement (just to understand the math and the concepts better) a function that computes the expected value of a circuit given the counts collected in the computational basis and an observable.

I tried to search on the Internet and on the documentation but could not find anything related, so I decided to implement it from scratch.

However, I’m not able to reproduce the theoretical expected value. What I’m doing wrong? Can you help me?

Thank you!!

```
import numpy as np
OBS = qml.PauliY(0) @ qml.Identity(1)
dev = qml.device("default.qubit", wires=2, shots=1000)
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
qml.Hadamard(wires=1)
qml.CNOT(wires=[0, 1])
return qml.expval(OBS), qml.counts()
def state_to_vector(state):
"""Convert a binary string state to a computational basis vector."""
num_qubits = len(state)
index = int(state, 2)
state_vector = np.zeros((2**num_qubits,))
state_vector[index] = 1
return state_vector
def compute_expected_value(counts, observable):
probabilities = {k:v / sum(counts.values()) for k,v in counts.items()}
expected_value = 0
for state, probability in probabilities.items():
# Convert the state string to a state vector
statevector = state_to_vector(state)
# Compute the inner product <psi_i|O|psi_i>
expectation = np.dot(statevector.conj().T, np.dot(observable, statevector))
# Add the weighted expectation to the total expected value
expected_value += probability * expectation
return expected_value
expval, counts = circuit(0.5)
print(compute_expected_value(counts, OBS.matrix()))
print(expval)
```