Skip to content

Incorrect error message when conversion of ParameterExpression to float fails. #10191

@jlapeyre

Description

@jlapeyre

Environment

  • Qiskit Terra version: main branch
  • Python version: 3.11
  • Operating system: Linux

What is happening?

When using SymEngine, sometimes a ParameterExpression wraps a SymEngine expression that is equivalent to a float. But trying to convert the ParameterExpression to a float fails with an error claiming that there are unbound parameters, when in fact all parameters are bound.

How can we reproduce the issue?

The following prints True three times.

from qiskit import QuantumCircuit
from qiskit.circuit import Parameter, ParameterExpression

x = Parameter("x")
pex = 1j * x
pexb = pex.bind({x : 1j})
print(str(pexb) == '-1.0')
print(complex(pexb) == -1)
print(isinstance(complex(pexb), complex))

But this fails:

float(pexb)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
File ~/qiskit/qiskit-terra/qiskit/circuit/parameterexpression.py:474, in ParameterExpression.__float__(self)
    473 try:
--> 474     return float(self._symbol_expr)
    475 # TypeError is for sympy, RuntimeError for symengine

File symengine_wrapper.pyx:1151, in symengine.lib.symengine_wrapper.Basic.__float__()

File symengine_wrapper.pyx:976, in symengine.lib.symengine_wrapper.Basic.n()

File symengine_wrapper.pyx:4346, in symengine.lib.symengine_wrapper.evalf()

RuntimeError: Not Implemented

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
Cell In[17], line 1
----> 1 float(pexb)

File ~/qiskit/qiskit-terra/qiskit/circuit/parameterexpression.py:477, in ParameterExpression.__float__(self)
    475 # TypeError is for sympy, RuntimeError for symengine
    476 except (TypeError, RuntimeError) as exc:
--> 477     raise TypeError(
    478         "ParameterExpression with unbound parameters ({}) "
    479         "cannot be cast to a float.".format(self.parameters)
    480     ) from exc

TypeError: ParameterExpression with unbound parameters (set()) cannot be cast to a float.

The error message is misleading. The attempt made to cast to a float failed, but for a different reason.

What should happen?

Maybe

Any suggestions?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions