Chuyển công thức toán học thành latex bằng python

Posted by Hao Do on November 16, 2022

Chuyển công thức toán học thành latex bằng python

Tìm hiểu latexify

Cài đặt thư viện

1
2
# Restart the runtime before running the examples below.
!pip install latexify-py==0.2.0

Import latexify into your code

1
2
3
4
import math  # Optionally
import latexify

latexify.__version__

Example

Example 1

1
2
3
4
5
6
7
@latexify.function
def 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 expression.
solve  # Display the MathJax.

Example 2

1
2
3
4
5
6
# latexify.expression works similarly, but does not output the signature.
@latexify.expression
def solve(a, b, c):
  return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)

solve

Example 3

1
2
3
4
5
6
# latexify.expression works similarly, but does not output the signature.
@latexify.expression
def solve(a, b, c):
  return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)

solve

Example 4

1
2
3
4
5
6
7
8
@latexify.function
def sinc(x):
  if x == 0:
    return 1
  else:
    return math.sin(x) / x

sinc

Example 5

1
2
3
4
5
6
7
8
9
10
11
# Elif or nested else-if are unrolled.
@latexify.function
def fib(x):
  if x == 0:
    return 0
  elif x == 1:
    return 1
  else:
    return fib(x-1) + fib(x-2)

fib

Example 6

1
2
3
4
5
# Some math symbols are converted automatically.
@latexify.function(use_math_symbols=True)
def greek(alpha, beta, gamma, Omega):
  return alpha * beta + math.gamma(gamma) + Omega
greek

Example 7

1
2
3
4
5
6
7
8
9
10
11
12
# 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

Example 8

1
2
3
4
5
6
7
8
9
# 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 * a
    return numerator / denominator

f

Full ipynb

Tài liệu tham khảo

Machine learning cơ bản

Hết.