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

Use hash of numeric value for bound parameter expressions (backport #12488) #12548

Merged
merged 1 commit into from
Jun 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions qiskit/circuit/parameterexpression.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,9 @@ def __int__(self):
raise TypeError("could not cast expression to int") from exc

def __hash__(self):
if not self._parameter_symbols:
# For fully bound expressions, fall back to the underlying value
return hash(self.numeric())
return hash((self._parameter_keys, self._symbol_expr))

def __copy__(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
fixes:
- |
:class:`.ParameterExpression` was updated so that fully bound instances
that compare equal to instances of Python's built-in numeric types (like
``float`` and ``int``) also have hash values that match those of the other
instances. This change ensures that these types can be used interchangeably
as dictionary keys. See `#12488 <https://github.com/Qiskit/qiskit/pull/12488>`__.
1 change: 1 addition & 0 deletions test/python/circuit/test_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -1425,6 +1425,7 @@ def test_compare_to_value_when_bound(self):
x = Parameter("x")
bound_expr = x.bind({x: 2.3})
self.assertEqual(bound_expr, 2.3)
self.assertEqual(hash(bound_expr), hash(2.3))

def test_abs_function_when_bound(self):
"""Verify expression can be used with
Expand Down
Loading