import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.primitives import StatevectorEstimator
from qiskit.quantum_info import SparsePauliOp

theta = Parameter("theta")
qc = QuantumCircuit(1)
qc.ry(theta, 0)
estimator = StatevectorEstimator()


def energy(values: list[float]) -> np.ndarray:
    return estimator.run([(qc, SparsePauliOp("Z"), np.array(values).reshape(-1, 1))]).result()[0].data.evs


t = 0.8
shift = energy([t + np.pi / 2, t - np.pi / 2])  # décalage de ±π/2
small = energy([t + 1e-4, t - 1e-4])  # petite différence finie
print("pente par décalage ±π/2   :", round(float((shift[0] - shift[1]) / 2), 4))
print("pente par petit écart     :", round(float((small[0] - small[1]) / 2e-4), 4))
print("dérivée exacte, -sin(0,8) :", round(float(-np.sin(t)), 4))
