latx — Symbolic Expression Compiler
Build symbolic expression trees from variables, constants, arithmetic, and transcendental functions. Compile them to fast callable functions. Pure stdlib, zero dependencies.
Why it exists: latx bridges the gap between symbolic algebra and numerical computation. Define an expression symbolically, use operator overloading (+, *, sin, etc.), then compile it to a Python function that evaluates the expression for given inputs. This is useful for defining mathematical models, computing gradients by hand, and separating model specification from evaluation.
Primitives
from latpy.latx import Var, Const
Class |
Description |
|---|---|
|
Symbolic variable with a string name |
|
Constant value (converted to |
x = Var("x")
c = Const(3.14)
Expressions
from latpy.latx import (
Expr, Add, Sub, Mul, Div, Pow, Neg,
Sin, Cos, Exp, Log,
)
All expression types support operator overloading:
Python Expression |
latx Node |
Description |
|---|---|---|
|
|
Addition |
|
|
Subtraction |
|
|
Multiplication |
|
|
Division |
|
|
Power |
|
|
Negation |
|
|
Sine (radians) |
|
|
Cosine |
|
|
Exponential |
|
|
Natural logarithm |
Expressions compose naturally:
x = Var("x")
expr = x * x + 2.0 * x + 1.0 # (x² + 2x + 1)
Compilation
from latpy.latx import compile
Signature |
Description |
|---|---|
|
Compile expression tree to callable function |
The compiled function takes positional arguments matching the variables in order, and returns a single float.
x = Var("x")
expr = Sin(x) + Cos(x)
f = compile(expr, x)
print(f(0.0)) # sin(0) + cos(0) = 1.0
# Multi-variable
x = Var("x")
y = Var("y")
f = compile(x * x + y * y, x, y)
print(f(3.0, 4.0)) # 25.0
Complete Example
from latpy.latx import Var, Sin, compile, pi
x = Var("x")
# Define a damped oscillator model
expr = Sin(x) * Exp(-x / 3.0)
f = compile(expr, x)
for val in [0.0, 1.0, 2.0, 5.0]:
print(f"f({val:.1f}) = {f(val):.4f}")