# `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 ```python from latpy.latx import Var, Const ``` | Class | Description | |-------|-------------| | `Var(name)` | Symbolic variable with a string name | | `Const(value)` | Constant value (converted to `float`) | ```python x = Var("x") c = Const(3.14) ``` --- ## Expressions ```python 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 | |-------------------|-----------|-------------| | `a + b` | `Add(a, b)` | Addition | | `a - b` | `Sub(a, b)` | Subtraction | | `a * b` | `Mul(a, b)` | Multiplication | | `a / b` | `Div(a, b)` | Division | | `a ** b` | `Pow(a, b)` | Power | | `-a` | `Neg(a)` | Negation | | `Sin(x)` | `Sin(x)` | Sine (radians) | | `Cos(x)` | `Cos(x)` | Cosine | | `Exp(x)` | `Exp(x)` | Exponential | | `Log(x)` | `Log(x)` | Natural logarithm | Expressions compose naturally: ```python x = Var("x") expr = x * x + 2.0 * x + 1.0 # (x² + 2x + 1) ``` --- ## Compilation ```python from latpy.latx import compile ``` | Signature | Description | |-----------|-------------| | `compile(expr, *variables) -> Callable` | Compile expression tree to callable function | The compiled function takes positional arguments matching the variables in order, and returns a single `float`. ```python 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 ```python 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}") ```