latexify
用于生成 LaTeX 数学公式的 Python 库。LaTeX 是一种基于 ΤΕΧ 的排版系统,对于展示复杂的数学公式表现极为出色。该项目可以用 Python 函数,轻松生成复杂的 LaTeX 数学公式描述。
一、安装库
pip install latexify-py
查看版本号:
import math # 可选
import numpy as np # 可选
import latexify
latexify.__version__
二、案例演示
我们需要以装饰器的形式进行使用,下面以求根公式为例:
def solve(a, b, c):
return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)
print(solve(1, 4, 3))
print(solve)
输出结果如下:
-1.0
<function solve at 0x0000020EBCF603A0>
用上装饰器后:
@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)
输出结果如下:
-1.0
\mathrm{solve}(a, b, c) = \frac{-b + \sqrt{ b^{2} - 4 a c }}{2 a}
单独查看solve函数:
solve
同时还可以直接用装饰器@latexify.expression
:
其他案例效果:
@latexify.function
def sinc(x):
if x == 0:
return 1
else:
return math.sin(x) / x
sinc
@latexify.function(reduce_assignments=True, use_math_symbols=True)
def transform(x, y, a, b, theta, s, t):
cos_t = math.cos(theta)
sin_t = math.sin(theta)
scale = np.array([[a,0,0], [0,b,0], [0,0,1]])
rotate = np.array([[cos_t, -sin_t, 0],[sin_t, cos_t,0], [0,0,1]])
move = np.array([[1,0,s], [0,1,t], [0,0,1]])
return move @ rotate @ scale @ np.array([[x], [y],[1]])
三、参考文献
https://github.com/google/latexify_py