I would like to symbolically represent one of variables as a partial derivative like:
dF_dx = symbols(‘dF/dx’)
so that display(dF_dx) would show it as:
Is there a way to do it? The official reference is not very clear to a newbie. Thank you.
Advertisement
Answer
_print_Derivative
currently decides based on requires_partial
if it’s going to use the rounded d symbol or not. The requires_partial
function checks how many free symbols the expression is using, if it’s using more than one symbol then it will use the rounded d symbol, otherwise it will just use d
instead.
To override this behaviour, we can just pass a custom LatexPrinter class to init_printing
from sympy import *
from sympy.printing.latex import LatexPrinter
from sympy.core.function import _coeff_isneg, AppliedUndef, Derivative
from sympy.printing.precedence import precedence, PRECEDENCE
class CustomPrint(LatexPrinter):
def _print_Derivative(self, expr):
diff_symbol = r'partial'
tex = ""
dim = 0
for x, num in reversed(expr.variable_count):
dim += num
if num == 1:
tex += r"%s %s" % (diff_symbol, self._print(x))
else:
tex += r"%s %s^{%s}" % (diff_symbol,
self.parenthesize_super(self._print(x)),
self._print(num))
if dim == 1:
tex = r"frac{%s}{%s}" % (diff_symbol, tex)
else:
tex = r"frac{%s^{%s}}{%s}" % (diff_symbol, self._print(dim), tex)
if any(_coeff_isneg(i) for i in expr.args):
return r"%s %s" % (tex, self.parenthesize(expr.expr,
PRECEDENCE["Mul"],
is_neg=True,
strict=True))
return r"%s %s" % (tex, self.parenthesize(expr.expr,
PRECEDENCE["Mul"],
is_neg=False,
strict=True))
def custom_print_func(expr, **settings):
return CustomPrint().doprint(expr)
x = symbols('x')
F = Function('F')(x)
init_printing(use_latex=True,latex_mode="plain",latex_printer=custom_print_func)
dF_dx = F.diff(x)
display(dF_dx)
OUTPUT:
See this post as well on how to use a custom latex printer.
All the code in this post is available in this repo.