Sympy Error when using POLY with SQRT

五迷三道 提交于 2019-12-24 08:38:46

问题


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?


回答1:


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.




回答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


来源:https://stackoverflow.com/questions/43660851/sympy-error-when-using-poly-with-sqrt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!