Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update qml.expval to correctly cast value type #6939

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
3 changes: 3 additions & 0 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,9 @@

<h3>Bug fixes 🐛</h3>

* `qml.expval` now longer silently casts to a real number when observable coefficients are imaginary.
andrijapau marked this conversation as resolved.
Show resolved Hide resolved
[(#6939)](https://github.com/PennyLaneAI/pennylane/pull/6939)

* `qml.capture.PlxprInterpreter` now correctly handles propagation of constants when interpreting higher-order primitives
[(#6913)](https://github.com/PennyLaneAI/pennylane/pull/6913)

Expand Down
3 changes: 1 addition & 2 deletions pennylane/measurements/expval.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,5 +162,4 @@ def _calculate_expectation(self, probabilities):
Args:
probabilities (array): the probabilities of collapsing to eigen states
"""
eigvals = qml.math.cast_like(self.eigvals(), 1.0)
return qml.math.dot(probabilities, eigvals)
return qml.math.dot(probabilities, self.eigvals())
11 changes: 11 additions & 0 deletions tests/measurements/test_expval.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,17 @@ def qnode():
class TestExpval:
"""Tests for the expval function"""

@pytest.mark.parametrize("coeffs", [1, 0.5, 0.5j, 0.5 + 0.5j])
def test_expected_dtype(self, coeffs):
"""Test that the return type of the expval function is correct"""

@qml.qnode(qml.device("default.qubit"))
def circuit(coeffs):
return qml.expval(coeffs * qml.PauliZ(0))

res = circuit(coeffs)
assert np.allclose(res, coeffs)
andrijapau marked this conversation as resolved.
Show resolved Hide resolved

@pytest.mark.parametrize("shots", [None, 1111, [1111, 1111]])
def test_value(self, tol, shots, seed):
"""Test that the expval interface works"""
Expand Down