Skip to main content

Module lambdify

Module lambdify 

Source
Expand description

Compiled numeric closures (CompiledFn, CompiledFnVec). Compile symbolic expressions to callable numerical functions.

Ex::compile lowers one or more expressions into a compact stack-VM program after a shared common-subexpression-elimination pass. The program is wrapped in CompiledFn (scalar) or CompiledFnVec (vector-valued) handles that are Clone + Send + Sync and evaluate without touching the arena or taking any locks.

Every numerically evaluable [ExprNode] is supported, including the special functions (Γ, ln Γ, ψ, erf/erfc and their inverses erfinv/erfcinv, Lambert W, Beta, factorials, binomials), Bessel functions and orthogonal polynomials with integer order, integer sequences, piecewise expressions and boolean/relational nodes (represented as 0.0/1.0). The special-function algorithms live in the crate-internal numeric_rt module and are shared with the Rust code generator, so compile() and to_rust_fn() agree bit for bit on those routines.

Symbol-free subexpressions are decided at compile time like the code emitters decide them: a real constant is folded to its certified f64 value, and a constant that is not real (atanh(9), asin(2), (-8)^(1/3)) is an error (NotImplemented, “the constant … is not real”), since a real-valued function cannot represent it.

One rule, no exceptions: a compiled function returns the value evalf gives (principal branches over ℂ, SymPy’s meaning), or NaN where that value is not real. So x^(p/q) of a negative x is NaN for every non-integer p/q — odd denominators included (the principal (-8)^(1/3) is 1 + √3·i; before 0.30 the compiled value was the real root −2, and a Cardano formula from solve compiled to a different root); the real root is real_root (sign(x)·|x|^(1/q)), which compiles to −2. loggamma(x) is NaN for a negative non-integer x (its value there is ln|Γ(x)| − iπ⌈−x⌉); the real ln|Γ(x)| is ln(abs(gamma(x))), lowered to the overflow-safe lgamma.

The compiler never recurses over the expression tree — it uses an explicit work stack — so arbitrarily deep expressions are safe.

Structs§

CompiledFn
A compiled scalar function f(x₁, …, xₙ) → f64.
CompiledFnVec
A compiled vector-valued function F(x₁, …, xₙ) → (f₁, …, fₖ).