gpt4 book ai didi

python - 在 Python 中找到多项式的有理根

转载 作者:行者123 更新时间:2023-12-03 19:13:16 25 4
gpt4 key购买 nike

我在 Python 的 sympy.solvers 中解决多项式时遇到了一个小问题.我想要的是找到有理根,而不是无理根。我的尝试如下 -

from sympy.solvers import solve
from sympy import Symbol
from fractions import Fraction

b_2=0
b_4= -10
b_6=32
b_8=-25

x_2p=-7/4

x = Symbol('x', real=True)
solution=solve(((4*x**3+b_2*x**2+2*b_4*x+b_6)*x_2p-(x**4-b_4*x**2-2*b_6*x-b_8)), x)
R=solution
if len(R) != 0:
print(Fraction(R[1]))

我得到以下错误 -
Traceback (most recent call last):
File "C:\Users\Roy\Desktop\EXP_2704 - Copy.py", line 16, in <module>
print(Fraction(R[1]))
File "C:\Program Files\Python37\lib\fractions.py", line 161, in __new__
raise TypeError("argument should be a string "
TypeError: argument should be a string or a Rational instance

请注意,我需要从 float 中获得准确的分数。

我怎样才能找到有理根?

最佳答案

如果您使用 real_roots您将获得一个可以以任意精度计算的 CRootOf 实例。使用你的初始化和以下我得到:

>>> from sympy import Rational, real_roots
>>> eq = ((4*x**3+b_2*x**2+2*b_4*x+b_6)*x_2p-(x**4-b_4*x**2-2*b_6*x-b_8)); eq
-x**4 - 7.0*x**3 - 10*x**2 + 99.0*x - 81.0
>>> real_roots(_)
[1, CRootOf(x**3 + 8*x**2 + 18*x - 81, 0)]
>>> r=_[1]
>>> Rational(r.n(2))
133/64
>>> Rational(r.n(20))
613677434358103191805/295147905179352825856

关于python - 在 Python 中找到多项式的有理根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61465481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com