Using latexify-py to Generate LaTeX Mathematical Formulas in Python
This article introduces the latexify-py Python library for converting Python functions into LaTeX mathematical expressions, covering installation, version checking, example code using decorators, and displaying the generated LaTeX output, with screenshots and links for further reference.
latexify-py is a Python library that automatically generates LaTeX mathematical formulas from Python functions, leveraging LaTeX's powerful typesetting capabilities for complex equations.
Installation
<code>pip install latexify-py</code>After installation you can verify the version:
<code>import math
import numpy as np # optional
import latexify
latexify.__version__</code>The version output is '0.4.2' .
Basic usage example
Define a function that solves a quadratic equation and call it:
<code>def solve(a, b, c):
return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)
print(solve(1, 4, 3))
print(solve)</code>Output:
<code>-1.0
<function solve at 0x1124f28e0></code>Applying the @latexify.function decorator converts the function into a LaTeX expression:
<code>@latexify.function
def solve(a, b, c):
return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)
print(solve(1, 4, 3))
print(solve)</code>Output now includes the LaTeX formula:
<code>-1.0
\mathrm{solve}(a, b, c) = \frac{-b + \sqrt{ b^{2} - 4 a c }}{2 a}</code>You can also use the @latexify.expression decorator for similar results, and the library supports many other examples, as shown in the accompanying screenshots.
For more details and additional examples, visit the project repository: https://github.com/google/latexify_py .
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.