多项式 x^3 - 3x + 1 的三个(实数)根相加为 0.但是 sympy 似乎不能简化这个根的总和:
>>>从 sympy 导入 *>>>从 sympy.abc 导入 x>>>rr = real_roots(x**3 -3*x + 1)>>>总和(rr)CRootOf(x**3 - 3*x + 1, 0) + CRootOf(x**3 - 3*x + 1, 1) + CRootOf(x**3 - 3*x + 1, 2)函数simplify 和radsimp 不能简化这个表达式.然而,最小多项式计算正确:
>>>最小多项式(总和(rr))_X由此我们可以得出结论,总和为0.有没有一种直接的方法可以让 sympy 简化这个根的总和?
解决方案如果可能,以下函数计算等于代数项的有理数:
import sympy as sp# 尝试将代数项简化为有理数def try_simplify_to_rational(expr):尝试:float(expr) # 表达式计算结果为实数吗?minPoly = sp.poly(sp.minimal_polynomial(expr))print('最小多项式:', minPoly)如果 len(minPoly.monoms()) == 1: # minPoly == x返回 0如果 minPoly.degree() == 1: # minPoly == a*x + ba,b = minPoly.coeffs()返回 sp.Rational(-b, a)除了类型错误:pass # 表达式不计算为实数除了 sp.polys.polyerrors.NotAlgebraic:pass # 表达式不计算为代数数除了例外作为 exc:打印(意外异常:",str(exc))print('化简为有理数不成功')return expr # 化简不成功查看工作示例:
x = sp.symbols('x')rr = sp.real_roots(x**3 - 3*x + 1)# 根之和等于 (-1)* x^2 的系数,这里为 0打印(sp.simplify(sum(rr)))打印(try_simplify_to_rational(sum(rr)))# ->0在sympy issue #19726.
The three (real) roots of the polynomial x^3 - 3x + 1 sum up to 0. But sympy does not seem to be able to simplify this sum of roots:
>>> from sympy import * >>> from sympy.abc import x >>> rr = real_roots(x**3 -3*x + 1) >>> sum(rr) CRootOf(x**3 - 3*x + 1, 0) + CRootOf(x**3 - 3*x + 1, 1) + CRootOf(x**3 - 3*x + 1, 2)The functions simplify and radsimp cannot simplify this expression. The minimal polynomial, however, is computed correctly:
>>> minimal_polymial(sum(rr)) _xFrom this we can conclude that the sum is 0. Is there a direct way of making sympy simplify this sum of roots?
解决方案The following function computes the rational number equal to an algebraic term if possible:
import sympy as sp # try to simplify an algebraic term to a rational number def try_simplify_to_rational(expr): try: float(expr) # does the expression evaluate to a real number? minPoly = sp.poly(sp.minimal_polynomial(expr)) print('minimal polynomial:', minPoly) if len(minPoly.monoms()) == 1: # minPoly == x return 0 if minPoly.degree() == 1: # minPoly == a*x + b a,b = minPoly.coeffs() return sp.Rational(-b, a) except TypeError: pass # expression does not evaluate to a real number except sp.polys.polyerrors.NotAlgebraic: pass # expression does not evaluate to an algebraic number except Exception as exc: print("unexpected exception:", str(exc)) print('simplification to rational number not successful') return expr # simplification not successfulSee the working example:
x = sp.symbols('x') rr = sp.real_roots(x**3 - 3*x + 1) # sum of roots equals (-1)*coefficient of x^2, here 0 print(sp.simplify(sum(rr))) print(try_simplify_to_rational(sum(rr))) # -> 0A more elaborate function computing also simple radical expressions is proposed in sympy issue #19726.
更多推荐
如何使 sympy 简化为零的部首表达式
发布评论