BlockEncoding.expectation_value#
- BlockEncoding.expectation_value(operand_prep: Callable[[...], Any], shots: int = 100, backend: BackendClient = None) Callable[[...], Any][source]#
Measures the expectation value of the operator using the Hadamard test protocol.
For a block-encoded Hermitian operator \(A\) and a state \(\ket{\psi}\), this method measures the expectation value \(\langle\psi|A|\psi\rangle\).
- Parameters:
- operand_prepCallable
A function
operand_prep(*args)that prepares and returns the operand QuantumVariables.- shotsint
The amount of samples to take to compute the expectation value. The default is 100.
- backendBackendClient
The backend on which to evaluate the quantum circuit. By default the Qrisp simulator is used. Ignored in Jasp mode.
- Returns:
- Callable
A function
ev_function(*args)with the same signature asoperand_prepreturning- Jasp mode:
a Jax array containing the expactation value,
- Standard mode:
a NumPy float representing the expectation value.
- Raises:
- TypeError
If
operand_prepis not a callable object.- ValueError
If the number of provided operands does not match the required number of operands (self.num_ops).
Notes
Precision: The number of shots \(N\) required for target precision \(\epsilon\) scales quadratically with the inverse precision \((N\propto 1/\epsilon^2)\).
Examples
Example 1: Jasp Mode (Dynamic Execution)
import numpy as np from qrisp import * from qrisp.block_encodings import BlockEncoding from qrisp.operators import X, Y, Z H = X(0)*X(1) + 0.5*Z(0)*Z(1) BE = BlockEncoding.from_operator(H) def operand_prep(phi): qv = QuantumFloat(2) ry(phi, qv[0]) return qv @jaspify(terminal_sampling=True) def main(BE): ev = BE.expectation_value(operand_prep, shots=10000)(np.pi / 4) return ev ev = main(BE) print(ev) # 0.3429
Example 2: Standard Mode (Static Execution)
# Using the same Hamiltonian and prep function from the previous example ev = BE.expectation_value(operand_prep, shots=10000)(np.pi / 4) print(ev) # 0.3426