DEV Community

Davide Gazzè
Davide Gazzè

Posted on

From python function to latex description using latexify_py

Hi everyone,
this is a small post about a simple, but an interesting project that generates LaTeX math descriptions from Python functions.
As usual, writing code is also an enjoyable activity, however, in the end, writing documentation is needed. Unfortunately, writing just text is not always sufficient, and some diagram is always useful. If you want, you can use PlantUML (more details are available here,
and here).
However, also mathematical functions are worthy of proper documentation. For these, normally, in academics, and industry, you can use Latex, read
here for an introduction. However, writing mathematical functions is time-consuming, the best would write the code, and use software that writes the latex formula for you.
This project is the goal of latexify_py.
The official notebook is available on Google Colab.

Installation

The installation of the package is simple:

# Install
pip install latexify-py==0.2.0
Enter fullscreen mode Exit fullscreen mode

To ensure the correctness type:

import math
import latexify

latexify.__version__
Enter fullscreen mode Exit fullscreen mode

the output will be:

0.2.0

One of the official examples is:

@latexify.function(reduce_assignments=True)
def solve(a, b, c):
  return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)

solve
Enter fullscreen mode Exit fullscreen mode

the output is:

Image description

Moreover, some math symbols, like alpha, beta, gamma, and delta, are converted automatically like:

@latexify.function(use_math_symbols=True)
def f0(alpha, beta, gamma, omega, delta):
  return alpha * beta + gamma - omega * delta

f0
Enter fullscreen mode Exit fullscreen mode

the output is:

Image description

The complete list is available here.
For example, we will implement the Collatz conjecture.
The conjecture concerns the following algorithm:

  • Take a positive integer n.
  • If n = 1, the algorithm ends.
  • If n is even, divide by two; otherwise multiply by 3 and add 1.

if you iterate the function, the result will converge to 1.

The code is the following:

@latexify.function(reduce_assignments=True)
def collatz(value):
  if value % 2 == 0:
    value = value / 2
  else:
    value = 3 * value + 1 

collatz
Enter fullscreen mode Exit fullscreen mode

The output is:

Image description

very impressive, is it?

Summary

In this post, we see some practical examples of the package latexify_py. You can see the results in this Google Colab Notebook.
Finally, this project is currently hosted on https://github.com/google but is not officially supported by Google.
I hope this project will be expanded with some features, like the support of for.

Top comments (0)