If you have any questions, please ask it in the issue tracker.
Install latexify
Import latexify into your code
import math # Optionalimport numpy as np # Optionalimport latexifylatexify.__version__
'0.4.2'
Examples
@latexify.functiondef solve(a, b, c):return (-b + math.sqrt(b**2-4*a*c)) / (2*a)print(solve(1, 4, 3)) # Invoking the function works as expected.print(solve) # Printing the function shows the underlying LaTeX source.solve # Displays the expression.# Writes the underlying LaTeX source into a file.withopen("compiled.tex", "w") as fp:print(solve, file=fp)
-1.0
\mathrm{solve}(a, b, c) = \frac{-b + \sqrt{ b^{2} - 4 a c }}{2 a}
# latexify.expression works similarly, but does not output the signature.@latexify.expressiondef solve(a, b, c):return (-b + math.sqrt(b**2-4*a*c)) / (2*a)solve
\[ \displaystyle \frac{-b + \sqrt{ b^{2} - 4 a c }}{2 a} \]
# Function names, arguments, variables can be replaced.identifiers = {"my_function": "f","my_inner_function": "g","my_argument": "x",}@latexify.function(identifiers=identifiers)def my_function(my_argument):return my_inner_function(my_argument)my_function
\[ \displaystyle f(x) = g \mathopen{}\left( x \mathclose{}\right) \]
# Assignments can be reduced into one expression.@latexify.function(reduce_assignments=True)def f(a, b, c): discriminant = b**2-4* a * c numerator =-b + math.sqrt(discriminant) denominator =2* areturn numerator / denominatorf
\[ \displaystyle f(a, b, c) = \frac{-b + \sqrt{ b^{2} - 4 a c }}{2 a} \]
# latexify.algorithmic generates an algorithmic environment instead of an equation.@latexify.algorithmicdef fib(x):if x ==0:return0elif x ==1:return1else:return fib(x-1) + fib(x-2)fib
# Another example: latexify.algorithmic supports usual control flows.@latexify.algorithmicdef collatz(x): n =0while x >1: n = n +1if x %2==0: x = x //2else: x =3* x +1return ncollatz
$
\[\begin{array}{l} \mathbf{function} \ \mathrm{collatz}(x) \\ \hspace{1em} n \gets 0 \\ \hspace{1em} \mathbf{while} \ x > 1 \\ \hspace{2em} n \gets n + 1 \\ \hspace{2em} \mathbf{if} \ x \mathbin{\%} 2 = 0 \\ \hspace{3em} x \gets \left\lfloor\frac{x}{2}\right\rfloor \\ \hspace{2em} \mathbf{else} \\ \hspace{3em} x \gets 3 x + 1 \\ \hspace{2em} \mathbf{end \ if} \\ \hspace{1em} \mathbf{end \ while} \\ \hspace{1em} \mathbf{return} \ n \\ \mathbf{end \ function} \end{array}\]