In Sympy, is it possible to modify the way derivatives of functions are output with latex()? The default is quite cumbersome. This:
f = Function("f")(x,t)
print latex(f.diff(x,x))
will output
\frac{\partial^{2}}{\partial x^{2}} f{\left (x,t \right )}
which is quite verbose. If I prefer something like
f_{xx}
is there a way to force this behavior?
You can subclass the 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]))
Which works like
>>> MyLatexPrinter().doprint(f(x, y).diff(x, y))
'f_{x y}'
>>> MyLatexPrinter().doprint(Derivative(x, x))
'\\frac{d}{d x} x'
To use it in the Jupyter notebook, use
init_printing(latex_printer=MyLatexPrinter().doprint)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With