Sympy: Changing Derivatives of LaTeX

In Sympy, can I change the way we derive derived functions using latex ()? The default value is rather cumbersome. It:

f = Function("f")(x,t) print latex(f.diff(x,x)) 

displays

 \frac{\partial^{2}}{\partial x^{2}} f{\left (x,t \right )} 

which is pretty verbose. If I prefer something like

 f_{xx} 

Is there any way to force this behavior?

+5
source share
1 answer

You can subclass LatexPrinter and define your own _print_Derivative . Here is the current implementation.

Maybe something like

 from sympy import Symbol from sympy.printing.latex import LatexPrinter from sympy.core.function import UndefinedFunction class MyLatexPrinter(LatexPrinter): def _print_Derivative(self, expr): # Only print the shortened way for functions of symbols function, *vars = expr.args if not isinstance(type(function), UndefinedFunction) or not all(isinstance(i, Symbol) for i in vars): return super()._print_Derivative(expr) return r'%s_{%s}' % (self._print(Symbol(function.func.__name__)), ' '.join([self._print(i) for i in vars])) 

How does it work

 >>> MyLatexPrinter().doprint(f(x, y).diff(x, y)) 'f_{xy}' >>> MyLatexPrinter().doprint(Derivative(x, x)) '\\frac{d}{dx} x' 

To use it in a Jupyter laptop, use

 init_printing(latex_printer=MyLatexPrinter().doprint) 
+3
source

Source: https://habr.com/ru/post/1266597/


All Articles