Converting a python numeric expression to LaTeX

前端 未结 5 484
感动是毒
感动是毒 2020-12-08 03:00

I need to convert strings with valid python syntax such as:

\'1+2**(x+y)\'

and get the equivalent LaTeX:

$1+2^{x+y}$
         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 03:34

    Just a little fix to Geoff Reedy excellent answer:

    class GenerateSymbols(defaultdict):
        def __missing__(self, key):
            self[key] = sympy.Symbol(key)
            return self[key]
    

    Before it would not add the new item to the dict. Now you can use this with your expression:

    d= GenerateSymbols()    
    eq = '(-b-sqrt(b**2-4*a*c))/(2*a)'
    

    and you can further simplify it before converting it to LaTeX:

    sympy.latex(sympy.simplify(eval(eq,d)))
    

    and you get this:

    '$- \\frac{b + \\operatorname{sqrt}\\left(- 4 a c + b^{2}\\right)}{2 a}$'
    

提交回复
热议问题