我正在使用Python Sympy,解决二次方问题,并希望使用LaTex打印结果。例如,如果结果是x =(1 + sqrt(3))/ 2,我希望它通过LaTex打印为\ frac {1 + \ sqrt {3}} {2}。但是,Python Sympy要么将其拆分为两个分数,如\ frac {1} {2} + \ frac {\ sqrt {3}} {2},要么将因子分解为一半,如\ frac {1} {2 }(1 + \ sqrt {3})。我试图通过sympy.fraction(expr)返回分子并查看了其他文章(Sympy - fraction manipulation和其他文章),但没有人能够产生结果。
答案 0 :(得分:1)
查看how to override the default printers.
import sympy
from sympy.printing.latex import LatexPrinter # necessary because latex is both a function and a module
class CustomLatexPrinter(LatexPrinter):
def _print_Add(self, expr):
n, d = expr.as_numer_denom()
if d == sympy.S.One:
# defer to the default printing mechanism
super()._print_Add(expr)
return
return r'\frac{%s}{%s}' % (sympy.latex(n), sympy.latex(d))
# doing this should override the default latex printer globally
# adopted from "Examples of overloading StrPrinter" in the sympy documentation
sympy.printing.latex = lambda self: CustomLatexPrinter().doprint(self)
print(sympy.printing.latex((1 + sympy.sqrt(3)) / 2)) # \frac{1 + \sqrt{3}}{2}