1

I have the following code:

from sympy import *
a = Symbol('a')
p = Poly(sqrt(a), domain=QQ)
p.eval(a,2)

What I expect after eval is the square-root of 2. however what I get is:

ValueError: tuple.index(x): x not in tuple

Am I misunderstanding something here?

bwright
  • 896
  • 11
  • 29

2 Answers2

2

The actual full error is

Traceback (most recent call last):
  File "./sympy/polys/polytools.py", line 1701, in _gen_to_level
    return f.gens.index(sympify(gen))
ValueError: tuple.index(x): x not in tuple

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "./sympy/polys/polytools.py", line 2308, in eval
    j = f._gen_to_level(x)
  File "./sympy/polys/polytools.py", line 1704, in _gen_to_level
    "a valid generator expected, got %s" % gen)
sympy.polys.polyerrors.PolynomialError: a valid generator expected, got a

The issue is that

>>> Poly(sqrt(a))
Poly((sqrt(a)), sqrt(a), domain='ZZ')

You've given Poly an expression that isn't a polynomial, but it tries to create a polynomial out of it anyway, by making it a polynomial in sqrt(a) instead of just a.

In general, I would avoid this sort of thing, unless you explicitly know what you are doing. It's always good practice to pass the generators to Poly that you expect your expression to be a polynomial in.

>>> Poly(sqrt(a), a)
Traceback (most recent call last):
...
sympy.polys.polyerrors.PolynomialError: sqrt(a) contains an element of the generators set
asmeurer
  • 86,894
  • 26
  • 169
  • 240
0

Evaluating a polynomial means substituting for one of its generators. The problem is that you are trying to substitute for a, after creating a polynomial in sqrt(a).

Essentially you are treating a polynomial as an expression that happens to have polynomial form in sqrt(a). Accordingly, the command should be

p.as_expr().subs(a, 2)

which returns sqrt(2) as expected.