简体   繁体   中英

Sympy: Return fractions and not floats in solve

Consider the following example:

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))

This results in

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

How can I make this to print (automatically) fractions instead of floats?

Use 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 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM