Sympy:在求解中返回分数而不是浮点数

时间:2017-12-03 15:29:36

标签: python sympy

考虑以下示例:

from sympy import *
x = Symbol('x',real=True)
eq = x**4 + 4/9*x**2 - 13/9
sol = solve(eq,x)
print(latex(eq))
print(latex(sol))

这导致

x^{4} + 0.444444444444444 x^{2} - 1.44444444444444
\left [ -1.0, \quad 1.0\right ]

如何让它打印(自动)分数而不是浮点数?

1 个答案:

答案 0 :(得分:3)

使用Rational

>>> from sympy import *
>>> x = Symbol('x', real=True)
>>> eq = x**4 + Rational(4,9)*x**2 - Rational(13,9)
>>> sol = solve(eq, x)
>>> sol
[-1, 1]
>>> print (latex(eq))
x^{4} + \frac{4 x^{2}}{9} - \frac{13}{9}
>>> print(latex(sol))
\left [ -1, \quad 1\right ]