Skip to content

Commit

Permalink
Use hash of numeric value for bound parameter expressions (#12488)
Browse files Browse the repository at this point in the history
* Use hash of numeric value for bound parameter expressions

If a `ParameterExpression` has no unbound parameters, the underlying
bound value can be hashed instead of the tuple that accounts for the
symbolic expression. Doing this allows for the `ParameterExpression` to
match the hash for the numeric value it compares equal to.

Closes #12487

* Add release note
  • Loading branch information
wshanks committed Jun 11, 2024
1 parent 03d107e commit bc685d3
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 0 deletions.
3 changes: 3 additions & 0 deletions qiskit/circuit/parameterexpression.py
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,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

0 comments on commit bc685d3

Please sign in to comment.