Printing, LaTeX and code generation

SymPy · Advanced · 10 min

Derived formulas are only useful once they reach a paper, a notebook or production code.

SymPy has a family of printers that convert an expression tree to text:

  • str(e) and print(e): Python-like syntax that sympify can parse back.
  • srepr(e): the exact constructor tree, for debugging.
  • pprint(e) / pretty(e): 2D Unicode or ASCII art.
  • latex(e): LaTeX source for papers and slides, with options like mode="equation" or mul_symbol="dot". Jupyter renders expressions with LaTeX automatically after init_printing().

Code printers turn expressions into source code in other languages: ccode, cxxcode, fcode (Fortran), rust_code, jscode, octave_code, and pycode for plain Python. They translate functions and constants (pi becomes M_PI in C), and can assign to a variable with assign_to=. ccode(Piecewise(...)) becomes a ternary or if block.

For whole functions or modules, sympy.utilities.codegen.codegen generates complete C or Fortran source and header files, and autowrap compiles them into Python-callable extensions.

Two practical tips. First, run cse() (common subexpression elimination) before printing large expressions, so repeated parts are computed once. Second, mind numeric behaviour: printers emit literal translations, so a formula that is exact symbolically can still suffer cancellation in floating point.

Example

from sympy import symbols, latex, ccode, pycode, sqrt, sin, pi, Rational, srepr

x, y = symbols("x y")
e = sqrt(x**2 + y**2) * sin(pi * x) / 2

print(latex(e))       # \frac{\sqrt{x^{2} + y^{2}} \sin{\left(\pi x \right)}}{2}
print(ccode(e))       # (1.0/2.0)*sqrt(pow(x, 2) + pow(y, 2))*sin(M_PI*x)
print(ccode(e, assign_to="r"))
# r = (1.0/2.0)*sqrt(pow(x, 2) + pow(y, 2))*sin(M_PI*x);
print(pycode(e))      # (1/2)*math.sqrt(x**2 + y**2)*math.sin(math.pi*x)
print(srepr(Rational(1, 2) * x))  # Mul(Rational(1, 2), Symbol('x'))

Remember

  • latex() for documents; pprint() for terminals; srepr() for debugging
  • ccode, fcode, pycode and friends emit source in other languages
  • Apply cse() before generating code from large expressions

Check yourself

  1. You need to paste a derived formula into a C simulation. Which function fits best?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.sympy.org/latest/modules/printing.html