Features

The complete feature reference. README.md carries a one-or-two-sentence summary of each entry below and links here for the detail; this page is the long form, and the one to keep current when a feature grows.

For the API itself see the Scaladoc — an absolute link, because /api is produced by unidoc after mdoc has run, so a relative one fails mdoc’s link check. For a command-by-command listing of the REPL see the cheat sheet. The domain pages carry the worked examples: Expressions, Calculus, Matrices, Equations, Logic, Sequences, Control, Optimization and the REPL; MCP server covers using Leonardo from an AI assistant.

  • Expression Parsing: Parses mathematical expressions using a recursive descent parser based on scala-parser-combinators. Supports standard operators, mathematical functions (sin, cos, tan/tg, asin, acos, atan, exp, ln, log, log(x, b)), implicit multiplication, unary minus in any operand position (3 * -x, 2^-x), multi-character variable names (theta, x1, alpha), and built-in constants pi, e, eulergamma, goldenratio (with the glyphs π, γ, φ) and i (imaginary unit). The named constants are symbols: a formula keeps pi, exact mode answers sin(pi/6) as 1/2, and outside exact mode each evaluates to its Double. Logarithms: ln(x) is the natural log; log(x) is decimal (base-10); log(x, b) is the general base-b log computed as ln(x)/ln(b) — so log(1000, 10) = 3, log(8, 2) = 3.

  • Dual Evaluation: Expressions evaluate to either:
    • A numeric result (Double, or a complex value) if all variables are bound
    • A symbolic result (an AST node) if variables remain unbound
  • Complex Numbers: The imaginary unit i is a built-in constant (2 + 3i, 3i), sitting alongside pi and e. Arithmetic is a full field — i*i = -1, (2 + 3i)*(1 - i) = 5 + i, division and powers included — implemented as a _Complex(re, im) value that collapses back to a plain real whenever the imaginary part vanishes, so real math is untouched. The elementary functions exp, ln, log, sin, cos, tan accept complex arguments (exp(i*pi) = -1, Euler’s identity), and complex closure means roots and logarithms of negatives return their principal values: (-2)^0.5 = i√2, ln(-1) = iπ, (-8)^(1/3) is the principal complex cube root. Values display as (a + bi) (or bi / i when purely imaginary) and round-trip through the parser; a floating-point residual imaginary part rounds away at display, so exp(i*pi) prints -1.0. Genuinely undefined forms (ln(0), 0^-1, division by zero) still stay symbolic.

  • Variable Binding: Support for binding variables to numeric values, allowing mixed symbolic-numeric evaluation of complex expressions. Multi-character variable names are fully supported.

  • Rich AST Representation: Expressions are represented as a type-safe AST with nodes for:
    • Numbers and variables
    • Binary operations (addition, subtraction, multiplication, division)
    • Unary functions (absolute value — abs(x), doubling as the complex modulus and exact on an exact argument — exponential, logarithm, trigonometric, hyperbolic and reciprocal-trigonometric — sinh/cosh/tanh, asinh/acosh/atanh, sec/csc/cot, sech/csch/coth, with simplify normalising the ratio spelling into a single reciprocal node: 1/cos(x) → sec(x), cos(x)/sin(x) → cot(x))
    • Integer parts and the remainder: floor(x), ceil(x), round(x) (a tie going away from zero) and mod(a, b) (the sign of the divisor) — exact on exact input, a surd decided by integer arithmetic rather than by its working-precision reading, element-wise on a matrix; the derivative is zero between the jumps and differentiable excludes them; a definite integral of a staircase of a linear argument is split at its jumps (integral(floor(x), x, 0, 3) is 3, exact on exact input); a two-sided limit at a jump declines while each side answers
    • Power operations
    • Higher-order operators (derivatives, definite integrals by the fundamental theorem where the antiderivative is smooth on the interval and otherwise by certified adaptive Simpson, declining across a pole, indefinite integrals via a symbolic rule table with integration by parts, trig-power reduction formulas (including tan/sec/csc/cot powers), full rational-function partial fractions (repeated and complex roots at any degree, via square-free factorisation), non-linear u-substitution for f(g(x))·g'(x) forms — ∫ x·e^(x²), ∫ sin³x·cos x — that the linear chain rule cannot reach, trigonometric/hyperbolic substitution for radicals √(a²−x²) / √(a²+x²) / √(x²−a²) at any half-integer power ((4−x²)^(3/2) included), the Weierstrass half-angle substitution t = tan(x/2) for rational functions of sin/cos (∫ 1/(1+sin x), ∫ 1/(2+cos x)), the special integral functions Si/Ci/Ei/li/fresnelS/fresnelC as named answers to the classic non-elementary integrals (∫ sin x/x = Si(x), ∫ e^(−x²) = (√π/2)·erf(x)), and a data-driven table of ~64 entries transcribed from the standard references — tan, cot, sec, csc, the hyperbolics, the standalone inverse functions (asin…atanh), product-to-sum (sin(ax)cos(bx)), the general e^(ax)sin(bx) pair, and the symbolic-parameter algebraic/radical forms (1/(a²−v²) → atanh(v/a)/a, 1/√(v²+a²) → asinh(v/a), v^a, v·a^v) — table rules are parameterised, so a symbolic constant free of the integration variable is handled too (k^v → k^v/ln(k)), every entry carries the linear-argument chain rule (tan(2x+1) closes), and every entry is verified by a differentiate-back harness; when all of that declines, the integrand is normalised (constants out of a denominator, powers of one base merged, a polynomial power expanded) and retried term by term with the textbook substitutions — ln(u)·g by parts, odd powers of sin/cos, u = ax + b, w = x², x = u^q for fractional powers, x = eᵘ for f(ln x) — so x·√(1 − x), sin⁵x·cos⁸x, √x/(x² + x) and cos(ln x) close, and limits)
  • Matrix Domain: matrix literals parse as [[1, 2], [3, 4]] (a row vector is [[1, 2]]), with transpose(...), det(...), inv(...), and the ordinary +, -, *, / operators — M := [[1, 2], [3, 4]] then M * M works in the REPL, and :saved sessions restore matrix bindings. Matrices are grids of arbitrary expressions — numbers, variables, functions, even functionals — evaluated element-wise. When every element reduces to a number, the matrix collapses to a dense row-major Array[Double] value (_MatrixValue), on which sum, product (block-tiled for cache locality, parallel over row blocks above a work threshold), transpose, scalar multiplication, determinant (LU with partial pivoting), and inverse (Gauss–Jordan) run as array kernels; otherwise operations combine element-wise symbolically and stay symbolic until the free variables are bound. det(A) returns a scalar; inv(A) and the reciprocal spelling 1 / A return the inverse matrix (M / N is M · N⁻¹), staying symbolic when A is singular or non-square. Small symbolic matrices get a cofactor determinant and adjugate/det inverse. The calculus and structural algorithms (derive, integrate, simplify, expand) distribute element-wise over matrices, matrix sums, and transposes (d/dx [aᵢⱼ] = [daᵢⱼ/dx]); matrix products deliberately stay symbolic under differentiation, as they need the product rule. Scalar functions distribute element-wise over a matrix argument too: sin(A), exp(A), ln(A), etc. reduce to the matrix of per-element results (staying symbolic if an element leaves the function’s real domain). This holds for symbolic matrices as well — exp([[x, 1], [y, 0]]) becomes [[exp(x), 2.71828], [exp(y), 1.0]], folding numeric cells and keeping free-variable cells as f(cell) until they are bound. A square dense matrix can be raised to an integer power with the ordinary ^ operator or pow(A, n): A^0 is the identity, A^n multiplies A by itself (binary exponentiation), and negative powers invert first (A^-n = (A⁻¹)^n); non-square bases, non-integer exponents, and negative powers of a singular matrix stay symbolic.

  • Vector products, trace, shape and norms (F_0039, F_0160–F_0162, F_0173): dot(u, v) is the number Σ uᵢvᵢ (no conjugate, so a complex vector stays unevaluated), cross(u, v) the right-handed product of two 3-vectors in the first one’s shape, trace(A) a square matrix’s diagonal sum. size(A) is the row [[rows, cols]] (so r, c := size(A) names both) and size(A, 1) / size(A, 2) one dimension, in the operand’s tier; a number is 1×1, and an operand whose shape is not known stays unevaluated. norm(x) / norm(x, kind) read the operand’s shape — a row or column is a vector, anything else a matrix — with the 2-norm as the default either way (a matrix’s is its largest singular value, through the SVD rather than eigen(AᵀA)), and 1, inf, fro and, for a vector, any p ≥ 1. All four stay exact on exact cells and build a symbolic answer from symbolic ones where one exists; a Double 2-norm is scaled by its largest entry, so it neither overflows nor underflows on input whose norm is representable. The math editor’s ∥x∥ converts to norm(x).

  • Matrix exponential: expm(A) computes the matrix exponential e^A = Σ Aᵏ/k! — a different operation from A^n, which is repeated multiplication. It uses scaling and squaring with a degree-13 Padé approximant, resting on the identity e^A = (e^(A/2ˢ))^(2ˢ): A is scaled until its norm falls inside the approximant’s accurate radius, the approximant is evaluated there, and the result squared back. The obvious alternative — diagonalise and exponentiate the eigenvalues, V·diag(e^λ)·V⁻¹ — is deliberately not used, because it needs an eigenbasis and a defective matrix has none; since a repeated eigenvalue is ordinary rather than exotic, that route would return a confidently wrong answer for a Jordan block instead of refusing, and the closed-form expm([[λ,1],[0,λ]]) = e^λ·[[1,1],[0,1]] is pinned in the suite for that reason. Nilpotent matrices come out exactly (expm([[0,1],[0,0]]) is [[1,1],[0,1]], since the series terminates), and a rotation generator gives back the rotation matrix. Non-square arguments stay symbolic.

  • Maximum, minimum, clamp and softplus: two operations under two names, the numpy split. maximum(a, b, …) / minimum(…) join their arguments — the larger or smaller, and on matrices element by element, a number spreading over every cell, so maximum(u, 0) rectifies a whole column. max(v) / min(v) reduce one array to its extreme entry, over every entry whatever the shape (the mean(x) sample convention, not MATLAB’s column-wise rule). clamp(x, lo, hi) saturates element-wise against scalar or column bounds — actuator saturation for a multi-input plant — and softplus(x, k) = ln(1 + e^(k·x))/k is the smooth maximum(0, x), evaluated as (max(k·x, 0) + log1p(e^(−|k·x|)))/k so that a large k·x does not overflow. What has an order decides what is accepted: real numbers, exact ones returned exact since the result is a selection, and matrices of them; a complex value has none, a truth value is declined because its join is or under min–max but not under the product or lukasiewicz semantics, and a name with no value yet is never guessed to be a number. Derivatives go through the step and favour the first argument at a tie, a stated subgradient choice: derive(maximum(x, 2*x), x) is 1 at 0 — the textbook step(a−b)·a' + step(b−a)·b' would give 3 there, outside the subgradient [1, 2]. differentiable reports each kink as an excluded point, and the same correction reached the step itself: differentiable(step(x), x) is now x ≠ 0, where it used to answer false.

  • Block matrices: hcat(A, B, …) and vcat(A, B, …) join blocks side by side and stacked, blkdiag(A, B, …) places them on the diagonal, repmat(A, m, n) tiles one, kron(A, B) is the Kronecker product, ones(m, n) the all-ones matrix, and submatrix(A, r0, r1, c0, c1) slices rows r0..r1 and columns c0..c1 — 1-based and inclusive, the convention at(A, i, j) already uses, so the 1×1 slice holds exactly at(A, i, j). They all rearrange cells through one shared assembly, so the same call works on a numeric matrix, an exact one (whose cells stay exact — a blkdiag’s zero blocks are built exact beside exact blocks) and a symbolic one. A number counts as a 1×1 block in hcat, vcat, blkdiag and kron, the MATLAB reading; a free name is never guessed to be one, since it may later be bound to a matrix, so hcat(x, A) waits until x is bound rather than assuming a width. Non-conforming blocks and out-of-range or non-integer indices leave the call unevaluated, and a result above a million cells is refused before it is built (measured: a million cells assemble in about 0.13 s and hold about 96 MB; ten million took 1.9 s and nearly a gigabyte). sub was deliberately not reserved — too plausible a variable name — hence submatrix. For model-predictive control, mpcMatrices(A, B, C, Np, Nc) builds the prediction matrices [[Φ, Γ]] of Y = Φ·x + Γ·U from these, with the last control move held over the rest of the horizon (stated, because the other convention gives a different Γ).

  • Cholesky factorisation: chol(A) returns the lower-triangular L with a positive diagonal and A = L·Lᵀ for a symmetric positive-definite A — chol([[4, 2], [2, 3]]) is [[2, 0], [1, √2]]. The refusal is the feature as much as the factor: a non-square, asymmetric, indefinite, negative-definite or singular matrix stays unevaluated, which makes chol the cheapest test that a quadratic form is strictly convex. An asymmetric matrix is never factored from one triangle, since that would answer for a different matrix, and both tests are relative to the largest entry, so A and 10⁶·A always get the same verdict — an absolute threshold would be a claim about the matrix’s units. In exact mode the factor is exact, symmetry and every pivot’s sign decided exactly, and an irrational pivot root is kept as a surd: each column of L carries a single root, so L·Lᵀ gives back A exactly.

  • Singular values: svd(A) returns [[U, S, V]] with A = U·S·Vᵀ, the singular values on S’s diagonal largest first — the economy form by default (U m×k, S k×k, V n×k, k = min(m, n)), and svd(A, full) for square orthogonal U and V whose extra columns span the null spaces. The kernel is one-sided Jacobi, which never forms AᵀA and so never squares the condition number, and it is certified — a decomposition that does not reconstruct A with orthonormal factors stays unevaluated. Three answers read off it: rank(A) (or rank(A, tol)), pinv(A) the Moore–Penrose pseudo-inverse, and cond(A) the 2-norm condition number, inf for a singular matrix; and two orthonormal bases, nullspace(A) and orth(A) for the null space and the range, false when the subspace is trivial. rank, pinv, nullspace and orth share one definition of numerically zero, σ ≤ 0.5·10⁻ᵖ·σ_max at session precision p — relative to the largest singular value, so A and 10⁹·A always have the same rank — while cond reports finite values right up to the rounding floor, since its job is to say how near singular a matrix is. Exact input is decomposed in Double, as qr is (lu is exact on exact input); the work is capped at max(m, n)·min(m, n)² ≤ 10⁷ (a 200×200 matrix takes ~70 ms on the JVM and ~0.6 s in the browser), and a refused call says why at the prompt.

  • Equations: 10 * x = 2 * x + 1 parses as a relation; once all variables are bound, it evaluates to true/false using tolerance-based equality tied to the configured precision (so sin(pi) = 0 is true despite floating-point noise); two exact values are equal when they agree to the working precision, and the REPL says so when that, not exact equality, decided. Concrete matrices compare element-wise. derive, simplify, expand, and integrate apply to both sides. Equations are first-class values: h := x^2 = 4 stores the relation, and solve(h, x) then works. lhs == rhs is an explicit equality check (same semantics, but not accepted by solve()). solve(lhs = rhs, x) — or equivalently solve(h, x) for a named equation — solves for a variable: linear equations exactly (symbolic coefficients included, x = -b/a), quadratics via the discriminant (0, 1, or 2 real roots, ±√Δ closed forms when coefficients are symbolic), and transcendental or higher-degree forms numerically (sign-change scan plus bisection over [-100, 100], up to 8 roots). One solution prints as x = 0.125; several as [[x = -2.0, x = 2.0]]. A matrix equation can be solved for a scalar unknown: solve([[x, 2*x]] = [[3, 6]], x) decomposes into the per-cell equations, solves each, and keeps only the value that satisfies every cell (here x = 3); an inconsistent system such as [[x, x]] = [[1, 2]] has no solution and stays symbolic. The unknown may also be a matrix: with A and B bound, solve(A * X = B, X) returns the unique X = A⁻¹·B via the inverse kernel (singular or non-conforming A → no solution); solve(X * A = B, X) gives X = B·A⁻¹. Beyond the one-sided forms, a constant term is peeled to the right (solve(A * X + C = B, X) → A·X = B − C) and a matrix on each flank is inverted on both sides (solve(A * X * D = B, X) → X = A⁻¹·B·D⁻¹). Symbolic coefficients yield a symbolic matrix solution (cofactor expansion, ≤ 6×6). General linear matrix equations where X appears in several terms — the Sylvester equation solve(A * X + X * B = C, X), the Lyapunov equation solve(A * X + X * transpose(A) = C, X), scalar coefficients solve(2 * X = B, X) — are solved by Kronecker vectorization: each term s·L·X·R contributes s·(Rᵀ ⊗ L) to a dense linear system over vec(X), solved via the inverse kernel and reshaped back (exact coefficients are solved over the rationals with an exact answer, up to 36 vectorized unknowns, dense ones up to 400; a singular system — e.g. A and −B sharing an eigenvalue — has no solution).

  • Logic: the word connectives and, or, not, implies, xor, iff operate on the boolean literals true/false and on anything that reduces to a boolean — equations included, so x = 1 and y = 2 is a conjunction of two relations. Connectives bind looser than =/==, with precedence not > and > xor > or > implies > iff (implies right-associative, iff not chaining). and/or/implies short-circuit on a decisive left operand (false and X is false without evaluating X), and expressions with free variables stay symbolic until bound. Simplification applies constant folding, double negation, idempotence, complement, absorption, the combining law (a and b) or (a and not b) = a, the absorbed implication (a implies b) and a = a and b and De Morgan where it removes a negation (all but De Morgan gated on crisp operands); toCNF/toDNF produce conjunctive/disjunctive normal forms (De Morgan plus distribution, capped against exponential blow-up), at the prompt cnf(e)/dnf(e), and the REPL’s truth <expr> command prints a truth table over an expression’s free variables (up to 16), headed by the formula as typed, with a note when a ? comes from a relation; equivalent(f, g) asks whether two formulas agree on every row, which ==, a comparison of values, does not; mindnf(e)/mincnf(e) answer a minimal sum of products or product of sums by Quine–McCluskey and an exact minimum cover (the fewest terms, then the fewest literals; of several equally minimal forms one is answered, the first in a fixed order, and a note counts them; bounded by an atom cap and a work budget, since the cover is NP-hard); under pretty on a formula is written with the fewest brackets the precedence allows.

  • Three-valued (Kleene) Logic: the same connectives and the same min–max rule table carry a third truth value, unknown — the value carrier widens, the operators do not. unknown is a first-class value (bindable, printable, restored by :save) sitting at degree 0.5: not unknown is unknown (its negation fixpoint), while the crisp cases still decide (false and unknown is false, true or unknown is true) — which is exactly why the short-circuits stay valid unchanged. Crisp results collapse back to plain booleans, so the classical truth tables fall out of the graded table as a special case rather than a separate code path. The classical laws that fail at unknown (complement a and not a, a implies a, a xor a) are gated on the expression being free of graded degrees, so simplification never folds them away wrongly; truth3 <expr> prints the 3ⁿ table (up to 10 variables).
  • Symmetric Ternary Logic: the same three truth values spelled with the digits {-1, 0, 1} — the balanced ternary alphabet — instead of false/unknown/true, related by the affine map t = (s + 1) / 2. This is an encoding, not a second semantics: the min–max rule table is identical either way, so the Kleene identities restate verbatim (-1 and 0 is -1, 1 or 0 is 1, not 0 is 0). Switched per Environment (logic symmetric on at the REPL, persisted by :save), which means a bound variable participates too, not just literals. With the toggle off a bare 0 stays a plain number so nothing is silently reinterpreted, and ordinary arithmetic is untouched in both modes. Under the encoding the digit 0 counts as graded, so 0 and not 0 correctly stays 0 rather than folding to false by complement.

  • Fuzzy Logic: the same connectives over the full [0, 1] interval. truth(x) turns a scalar degree into a truth value (and is how a graded degree prints, so it round-trips through :save), while membership curves — trimf(x,a,b,c), trapmf(x,a,b,c,d), gaussmf(x,mean,sigma), sigmf(x,a,c) — and the hedges very(d) = d² / somewhat(d) = √d map crisp measurements into degrees. They evaluate to truth values, so very(trimf(t, 0, 10, 20)) and somewhat(h) composes with no cast at each step. Which t-norm combines degrees is an Environment parameter rather than a separate package: min–max (default), product (a·b / a+b−a·b), or Łukasiewicz (max(0,a+b−1) / min(1,a+b)) — all three agreeing with classical logic on the crisp values, so the boolean and three-valued tiers are untouched by the choice. Only min–max is a lattice, so idempotence and absorption hold for graded degrees there alone and simplification gates them accordingly. defuzz(e, v, lo, hi) collapses a membership curve back to a crisp value by centre of gravity, or with a fifth argument mom or bisector by the mean of the maxima or the area’s bisector, sampling through the same compiled-closure fast path Simpson’s rule uses.

  • Special Functions: the factorial family and the gamma function. fact(n) is exact for integers up to 170! and continues analytically past them (fact(0.5) is √pi/2); dfact(n) is the double factorial and mfact(n, k) the multifactorial with step k. Gamma(z) is the Lanczos approximation with the reflection formula for negative arguments, lgamma(z) its log-space companion that stays finite where Gamma itself overflows, and Beta(a, b) the beta function computed through lgamma so large arguments survive. Gamma and Beta are capitalised deliberately, so the lowercase gamma and beta stay available as ordinary variable names. The analytic tier extends the family with the error function erf/erfc, the digamma function (which is what makes Gamma and fact differentiable), the regularised incomplete gamma (gammaP/gammaQ) and incomplete beta (betaI), and Gamma over complex arguments. Poles, overflow and out-of-domain arguments stay symbolic rather than returning infinities, and the functions distribute element-wise over a matrix argument like the elementary ones.

  • Numeric Sequences: fib(n) — the library is named after Leonardo Pisano, after all — together with lucas, pell and jacobsthal, all one recurrence x(k) = p·x(k-1) + q·x(k-2) differing only in seeds and coefficients, so each keeps its own name while the recurrence has a single definition (lucas(n) and fib(n, 2, 1) are the same number by construction). Indexing is the standard one — fib(10) = 55, matching OEIS A000045 — and the classic “rabbit” pair is written explicitly as fib(n, 1, 1), which is the same sequence shifted by one. They are numeric, not integer, sequences: a recurrence needs only addition and multiplication, so fib(5, 1.5, -pi) is a legitimate call and exact seeds stay exact. That last point is not decoration — a Double stops representing Fibonacci numbers exactly at fib(78), so in exact mode fib(100) is 354224848179261915075 rather than an approximation (Binet’s formula is deliberately not used: elegant, but inexact past n ≈ 70). Alongside them: binom (generalised to a real upper index, so binom(-1, 3) = -1), catalan, and harmonic, which is rational-valued and shows the exact tier off nicely — harmonic(4) is 25/12. Finally tabulate(e, k, lo, hi) evaluates any expression over an integer range into a 1×n matrix: tabulate(binom(4, k), k, 0, 4) is a Pascal row, and because the result is an ordinary matrix, at, tuple assignment and :save all work on it unchanged — with sum(e, k, lo, hi) and product(e, k, lo, hi) as its counterpart, folding those terms rather than listing them. An exact term stays exact (sum(1/k, k, 1, 3) is 11/6), symbolic terms expand so simplify can collect them (sum(k*x, k, 1, 3) becomes 6x), and an empty range gives the operator’s identity — 0 and 1 — so sum(f, k, 1, n) reads correctly at n = 0 instead of declining a base case.

  • Vector Calculus: grad(f, x, y, z), div(F, x, y, z), curl(F, x, y, z), laplacian(f, x, y, z), plus jacobian(F, ...) and hessian(f, ...). A vector field is simply an n×1 matrix — div([[x^2], [y^3]], x, y) gives 2x + 3y^2, and curl([[-y], [x], [0]], x, y, z) gives [[0], [0], [2]] — so every existing matrix operation applies to a field unchanged. The coordinate tuple is always written out and ordered, never inferred, because it fixes the order of the result’s components. The coordinate-free identities hold (curl(grad f) = 0, div(curl F) = 0, laplacian = div∘grad). Shapes with no meaning stay symbolic rather than being guessed: a curl outside three dimensions (in 2-D the natural object is a scalar curl, a different result type), a component/coordinate count mismatch, a repeated coordinate, or a row vector. Cartesian, cylindrical and spherical coordinates are supported through an optional trailing keyword — laplacian(1/r, r, t, p, spherical) is 0, and div([[1/r], [0], [0]], r, t, z, cylindrical) is 0, both because the operators are written once in terms of the coordinate system’s scale factors rather than once per system. The curvilinear systems are three-dimensional and identify their coordinates by position, not by name (so you may call them anything). Both spherical conventions are available and differ in argument order rather than naming: spherical is the physics order (r, θ, φ) with θ the polar angle, and sphericalmaths the mathematics order with θ azimuthal and φ polar. Exchanging those two coordinates flips the handedness of the basis, so curl — being a pseudo-vector — carries the corresponding sign; the two conventions agree on the curl of the same physical field. Multivariate integration needs nothing extra — iterated integrals accept limits that depend on the outer variables, so integral(integral(x*y, y, 0, x), x, 0, 1) is 0.125.

  • Series Expansions: taylor(e, v, point, n) expands an expression as a truncated Taylor polynomial about a point, and maclaurin(e, v, n) is the special case centred on zero. The coefficients come from truncated power-series arithmetic — sums, products, quotients and constant powers by their recurrences, exp/ln/sin/cos/sinh/cosh by their differential equations, the reciprocal and quotient functions as quotients, and the inverse functions by integrating their algebraic derivatives — so the work grows with the square of the order rather than exponentially, and taylor(tan(x), x, 0, 20) is instant. A quotient that vanishes into 0/0 at the centre is cancelled first, so maclaurin(sin(x)/x, x, 6) is 1 - x^2/6 + x^4/120 - x^6/5040 and maclaurin(ln(sin(x)/x), x, 4) is -x^2/6 - x^4/180; a pole or a logarithm of zero at the centre has no Taylor series, and declines with a note naming the coefficient that is undefined there (laurent is the expansion such a point has). Every coefficient is an expression, so an exact input keeps exact coefficients and a free parameter stays symbolic. The centre need not be numeric: expanding about a symbolic a yields a genuine polynomial in (x − a) with f⁽ᵏ⁾(a) coefficients. The expansion variable stays free in the result, so binding it evaluates the polynomial and the series composes with derive, samples and the rest of the library. Order is capped at 20. A function the arithmetic does not cover (erf and the other special functions) is differentiated instead, and only that subexpression: its derivatives are held to 50 000 nodes, so taylor(erf(sin(x)), x, 0, 20) declines in well under a second, with a REPL note naming the order that outgrew the budget, instead of running for minutes. An expression whose derivative falls outside the rule table (digamma, which would need trigamma) returns unevaluated rather than a series with an unresolved derivative buried in it, and taylor, laurent and pade all say at the prompt why they declined.

  • Fourier Series: fourierSeries(e, v, period, n) expands a periodic function over one period centred on zero as a Fourier series a0/2 + sum of [ak*cos(kωv) + bk*sin(kωv)]. Unlike the Taylor tier this is a numeric expansion: each coefficient is a definite integral evaluated by the same Simpson path used for integral(f, x, a, b), so the period must be a concrete positive number. The classic results come out as expected — the sawtooth fourierSeries(x, x, 2*pi, 4) gives 2sin(x) - sin(2x) + (2/3)sin(3x) - (1/2)sin(4x), and x^2 gives a cosine-only series with constant term pi²/3. Coefficients are deliberately not chopped: a term that vanishes analytically comes back at the integrator’s noise floor rather than exactly zero, on the principle that cleanup is a display concern. Not to be confused with fourier(e, t, w), the Fourier transform.

  • Laurent Series: laurent(e, v, a, m, n) expands about a pole as Σ(k = −m..n) c_k·(v−a)ᵏ — a Laurent series, the expansion Taylor cannot provide at a singular point. The principal-part length m is optional: omitted, it is detected from the pole order reported by singularities. An essential singularity is refused rather than truncated — its principal part is infinite, and the discarded terms grow near the point instead of shrinking, so a truncation would not carry the contract the polynomial tiers do.

  • Pade Approximants: pade(e, v, m, n) builds the [m/n] rational approximant about zero — the quotient P/Q with deg P <= m, deg Q <= n and Q(0) = 1 whose Maclaurin series matches the function through order m + n. It is frequently far more accurate than the Taylor polynomial of the same total degree, because a rational function can model a nearby pole that no polynomial can: pade(exp(x), x, 1, 1) is the familiar (2 + x)/(2 − x), and pade(exp(x), x, 2, 2) beats maclaurin(exp(x), x, 4) at x = 1. A rational function reproduces itself exactly, and pade(f, x, m, 0) degenerates to the Taylor polynomial. The defining linear system is solved through the dense matrix inverse in core; a singular system (no [m/n] approximant in normal form) leaves the expression symbolic rather than dividing by zero.

  • Greek Notation: the special functions accept their Greek spellings — Γ(z) for Gamma(z) and β(x, y) for Beta(x, y) — and the REPL can insert the glyphs with an ALT-\ prefix (ALT-\ g, ALT-\ b; ALT-G also works directly). A prefix was chosen over one chord per symbol because ALT-B is already backward-word in emacs-style line editing, and because a prefix extends to further symbols without re-checking for collisions. Capital Greek Beta is deliberately not accepted: U+0392 is a homoglyph of Latin B, so it would be invisible which of the two had been typed; the visually distinct lowercase β is used instead. Both spellings parse to the same node and toString always emits the ASCII form, so saved scripts stay portable to terminals that cannot render or type these.

  • Limits: limit(expr, var, point) computes lim_{var → point} expr. What sampling cannot certify is read by a limit algebra (F_0286): the limits of the parts combined while the form is determinate, an indeterminate quotient read from two Taylor series at a point or from growth classes (exponential, power, logarithm) at infinity — so limit(n/2^n, n, inf), limit((1 + 2/x)^x, x, inf), limit(ln(t), t, 0, +) and limit(((x + h)^2 - x^2)/h, h, 0) answer, the last as 2x. With a free parameter the answer is generic and the REPL notes what it assumed (limit(x/(x - a), x, 2): assuming 2 - a != 0). Supports two-sided and one-sided limits (limit(1/x, x, 0, +) → inf; limit(1/x, x, 0, -) → -inf). Handles indeterminate forms via L’Hôpital’s rule (0/0 and ∞/∞, up to 5 steps), and limits at ±∞ for polynomial/rational functions, exp, ln, atan, and elementary compositions. inf is a built-in constant equal to +∞; -inf follows from unary minus.

  • Laplace & Fourier Transforms: laplace(f, t, s) computes the Laplace transform L{f(t)} via a symbolic rule table — constants (c → c/s), powers (t^n → n!/s^(n+1), capped at n ≤ 20), exponentials (e^(ct) → 1/(s−c)), sin(wt) → w/(s²+w²), cos(wt) → s/(s²+w²), linearity, and the first-shift theorem e^(at)·g(t) → G(s−a) applied recursively — so laplace(t*exp(-t), t, s) yields 1/(s+1)². fourier(f, t, w) is the two-sided Fourier transform, ∫ f(t)·e^(−iwt) dt over the whole line, computed as the Laplace transforms of the causal part and of the reflected anti-causal part at s = ±i·w — so fourier(exp(-abs(t)), t, w) is 2/(1 + w²) and the centred pulse step(t+1) − step(t−1) gives 2·sin(w)/w; fourierCausal(f, t, w) is the transform of f(t)·u(t) alone (fourierCausal(exp(-2*t), t, w) → 1/(2 + i·w)). Both answer only where the integral converges: every pole of each Laplace part must lie strictly left of the imaginary axis, unless it cancels in the whole transform as the pulse’s does. 1 and cos(t) would need Dirac deltas, which the library has no node for, and exp(-t) diverges as t → −∞, so they stay unevaluated with a note naming the pole, rather than the substituted rational the transform gave until 2026-10 (F_0141). Shapes outside the table stay symbolic.

  • z-transform: ztrans(x, n, z) computes the one-sided z-transform X(z) = Σ(n≥0) x[n]·z⁻ⁿ, the discrete counterpart of laplace and built on the same rule-table machinery: constant, linearity, unit step, geometric (aⁿ → z/(z−a)), exp(c·n), sine and cosine. Z{c} = c·z/(z−1) and not c/z — the Laplace analogue L{c} = c/s does not carry over, since a constant sequence is c at every index. The n-multiplied family (n → z/(z−1)², n² → z(z+1)/(z−1)³, n·aⁿ → a·z/(z−a)²) is not a set of table entries but a single rule, Z{n·x[n]} = −z·dX/dz, so the four cannot drift apart. invztrans(X, z, n) recovers the sequence by decomposing X(z)/z — the division is the technique, since every forward entry carries a factor of z in its numerator — with each z/(z−r)^j term inverting to C(n, j−1)·r^(n−j+1), so distinct and repeated real poles both work: invztrans(z/((z-1)*(z-2)), z, n) is 2ⁿ − 1 and invztrans(z/(z-2)^2, z, n) is n·2^(n−1). Three things are deliberately absent rather than approximated: the Kronecker delta (there is no discrete-impulse node), complex poles in the inverse (they invert to a damped oscillation this tier does not build), and the bilateral transform, which would need a region of convergence on every result or the inverse would have to guess between a causal and an anti-causal signal.

  • Discrete Fourier analysis: dft(x) and idft(X) transform a row or column of real or complex samples by the direct sum, the shape kept (up to 8192 samples, a work budget); conv(x, h) is discrete linear convolution, exact on exact input. The DTFT needs no function of its own: it is ztrans evaluated at z = e^(iω).

  • Inverse Laplace Transform: invlaplace(F, s, t) recovers f(t) from a rational F(s) = N(s)/D(s) with deg N < deg D — the dual of the forward table. Linearity peels sums and constant factors; the pole structure is read off by completing the square: linear denominators give b/(s−a) → b·e^(at), distinct real roots split via partial fractions into A·e^(r₁t) + B·e^(r₂t), a repeated root gives e^(at)·(N₁ + (N₀+N₁a)·t), and a complex-conjugate pair gives e^(at)·(N₁cos(wt) + …sin(wt)). So invlaplace(3/((s-2)^2+9), s, t) returns e^(2t)·sin(3t), and invlaplace(laplace(f, t, s), s, t) round-trips f. Denominators of degree ≥ 3 are decomposed by square-free factorisation and undetermined coefficients, so repeated poles invert too — 1/s^3 → t²/2, 1/((s-1)^2(s-2)), 1/(s^2+1)^2 — while a repeated irreducible quadratic past the second power, symbolic coefficients, and non-rational input stay symbolic.

  • Control systems: transfer functions, time and frequency response, stability, state space and discretisation — with no carrier type. A transfer function is an ordinary expression, so simplify, derive, substitute, the exact tier and the parser all apply to one for free; the price is that the frequency variable is an explicit argument everywhere (poles(g, s), never g.poles). Interconnection: series(G, H, s), parallel(G, H, s) and feedback(G, H, s), each returning one rational in lowest terms — feedback(1/(s*(s+2)), 1, s) is 1/(s²+2s+1), not the uncancelled quartic whose spurious roots at 0 and −2 would be reported as poles. feedback is negative feedback, stated because it cannot be inferred: a substantial part of the literature writes G/(1 − G·H), and choosing silently would make every closed-loop answer wrong for half its readers. Time response step(G, s, t) and impulse(G, s, t) are the inverse Laplace transform of G/s and G; step is arity-overloaded, so step(x) remains the Heaviside unit step. poles/zeros return _Values rather than Doubles because a complex pole is the interesting case — an oscillatory mode is a conjugate pair, and reducing to reals would drop exactly the systems the domain is about. isStable decides from the pole locations rather than a Routh–Hurwitz table (Routh’s degenerate cases each need a repair, and a mishandled one gives a wrong verdict instead of a refusal — routhTable is still there for inspection) and is strict, so marginal stability is not stability. At the prompt the poles and zeros are tfpoles(G, s)/tfzeros(G, s) — zeros(r, c) is already the zero matrix — beside routhTable(G, s) (the array as a padded matrix), controllable/observable and the matrices ctrb/obsv, single-input pole placement acker(A, B, poles) (Ackermann’s formula, certified by the eigenvalues it places), the browser’s rlocus root locus (closed-loop poles over a gain band, matched into continuous branches), isStable, isStableDiscrete, stateSpace and c2d(G, s, z, Ts, method) — zero- and first-order hold, Tustin (prewarped on request), impulse invariance, matched pole-zero, and forward and backward Euler, the method always named and each convention stated; dlsim(sys, u, x0) simulates a discrete state-space model over recorded inputs, with the states x[0] … x[N] on request — the final one included, so a run continues where it stopped. dare(A, B, Q, R) solves the discrete algebraic Riccati equation for its stabilising solution by structure-preserving doubling, certified by its own residual; dlqr adds the gain of the law u = −K·x and proves A − B·K stable, dlyap solves the Stein equation A·X·Aᵀ − X + Q = 0, and kalmanGain / kalmanStep are the steady-state and one-step Kalman filter, the second taking and returning the state and covariance (an update, then a prediction). A plant with no stabilising solution — not stabilisable, or an unstable mode the weight does not see — is declined with that reason rather than answered with a non-stabilising root. For a controller running in a Scala loop, the library also offers the MPC step’s numeric pieces (no prompt form): dense prediction matrices in the absolute and Δu formulations, the condensed quadratic programme with input, rate and (optionally soft) output bounds, disturbance-augmented models for offset-free tracking with their detectability test and steady-state target, and ARX order selection by AIC, BIC or FPE (see Control). bode/nyquist are one substitution s → iω riding the existing complex closure, and frequencyResponse/nyquistSweep are their swept forms — the two things a diagram needs that a plain sample cannot give it. The grid is geometric, because a response is read across decades and a linear grid of 200 points over 0.01 .. 100 puts 199 in the last decade and none near a corner at 0.1. The phase is unwrapped: atan2’s principal value is (−π, π], so a raw sweep of 1/(s+1)^3 reports +90° where the plant reads −270° — an artefact of the arctangent that every reader plotting a raw sweep inherits. Reported in dB and degrees, because that is what a Bode plot is; the raw pair stays available from bode. Unwrapping cannot tell a genuine half-turn step from a grid too coarse to resolve a fast one, so a sparse sweep across a lightly damped resonance unwraps wrongly — the remedy is points, and the caveat is stated rather than hidden. State space bundles (A, B, C, D) as the 1×4 matrix row lu/qr/eig already return, with controllable/observable — the second defined as the first on the dual pair, so they cannot disagree. A nonlinear model reaches it through linearize(F, G, x, u, x0, u0), the four Jacobians at an operating point with the state and input tuples ordered and explicit, and affine appending the offsets F(x0, u0), G(x0, u0) a non-equilibrium point needs; a point outside the domain, or a derivative that is not a real number there, is declined with the entry named. A black-box model comes from data through ARX identification: arx(u, y, na, nb, nk) fits y[k] = Σ aᵢ·y[k−i] + Σ bₗ·u[k−nk−l+1] by least squares for several inputs at once, in the predictor sign (MATLAB’s a is the negative of this one, stated because it cannot be inferred), and declines data that does not excite the model rather than fitting rounding; arx2tf(a, b, nk, z) and arx2ss(a, b, nk) turn the result into a transfer function and a state-space row, with the delay always an explicit argument. Several outputs are one coupled model (p×p blocks Aᵢ, returned stacked), whose transfer matrix is A(z)⁻¹B(z) and whose realisation is the block observer form, non-minimal and stated. Discretisation c2d/d2c always names its method (Zoh or Tustin), never defaults silently, since the two give different discrete poles; c2dExact uses the matrix exponential of [[A, B], [0, 0]]·Ts rather than A⁻¹(A_d − I)B, which is a correctness matter because the block form is defined for a singular A and any system with an integrator has one. Declined rather than approximated: a non-rational G such as a dead-time exp(−2s) (pade exists, and reaching for it is the user’s choice), an improper G in a time response (the impulsive term at t = 0 is not representable), an undeterminable coefficient sign, and d2c by zero-order hold.

  • Differential Equations: ode(rhs, y, t, t0, y0, target) solves the first-order initial-value problem y' = rhs(t, y), y(t₀) = y₀, and returns the solution value y(target). Linear equations y' = a(t)·y + b(t) are solved in closed form: constant coefficients directly (y' = y, y(0)=1 gives e exactly at t = 1; y' = 2y + 3 gives the affine-plus-exponential form), and variable coefficients via the integrating factor μ(t) = e^{∫p dt} (y' = -y + t → t − 1 + 2e^{-t}; y' = -y/(1+t) → 1/(1+t)), reusing the full indefinite-integration engine (so a forcing term like t·eᵗ closes by integration by parts). A free target, a free initial condition, or a symbolic coefficient yields a symbolic solution (ode(k*y, y, t, 0, 1, 1) → e^k). Non-linear shapes (y' = sin(y), y' = -y²) and linear ones whose coefficient integral has no closed form (y' = tan(t)·y) are integrated numerically with a fourth-order Runge–Kutta scheme (backward integration when target < t₀); a non-evaluable right-hand side or a symbolic target with no closed form stays symbolic. Linear systems use the same ode: when y0 is an n×1 column and the right-hand side is A*y, A*y + b or b + A*y with a constant square matrix A and column b, the answer is the state vector e^(A·τ)·y₀ plus the input term, τ = target − t₀ (ode([[0, 1], [-1, 0]] * y, y, t, 0, [[1], [0]], 1) is (cos 1, −sin 1)). It is computed by the matrix exponential of the augmented block [[A, b], [0, 0]]·τ — the kernel c2dExact uses — rather than through eigenvectors, so a defective A such as the double integrator [[0, 1], [0, 0]] and a singular A with a constant input both come out right where the eigen route and A⁻¹(Φ − I)b would not. A matrix coefficient bound to a name and a literal one behave alike. The system tier is numeric (τ, A, b, y₀ must fold). Time-varying and nonlinear systems — where no closed form exists in general — are integrated numerically: the state is either one name bound to the whole column (ode([[t, 0], [0, -t]] * y, y, t, 0, [[1], [2]], 1), or a nonlinear right-hand side through at(y, i, 1)) or a column of names, each bound to its component, so a system reads as written: ode([[v], [-x]], [[x], [v]], t, 0, [[1], [0]], 1) is (cos 1, −sin 1), and Lotka–Volterra is ode([[x - x*y], [x*y - y]], [[x], [y]], t, 0, [[2], [1]], 5). The answer is certified by step doubling: RK4 runs with n and 2n steps and answers only when the two agree within the tolerance = uses, relative to the state’s own size (so the same problem in other units is decided alike), so a stiff or under-resolved system is refused — with the reason as a REPL note — rather than answered with a confident wrong number; a right-hand side that is not a conforming column is never broadcast. The integrator is also public, with the method always named: odeStep(F, y, t, t0, y0, h, method) is the state one step after t0, and odeSolve(F, y, t, t0, y0, t1, h, method) the trajectory, one row [t, state…] per output time with t1 always the last. euler and rk4 take exactly one uncertified step of size h — the step is the caller’s, which is what a controller simulation wants — while rk45 is adaptive Dormand–Prince, h then being the output spacing. A name bound in the session, such as a control input, is a constant during a step.

  • Relations and logic: = builds a solvable equation, == an equality test, and <, >, <=, >=, != compare — all reducing to booleans that compose with and/or/not/implies, so x > 0 and x < 10 is an ordinary expression. Comparisons of exact operands decide equality at the working precision — every irrational in the exact tier is carried to it, so (2^(1/2))^2 == 2 is true and the REPL notes that it holds to that precision, not exactly — and of other operands at the display precision, with == and the orderings agreeing so that precisely one of <, ==, > ever holds.

  • Inequality solving: solve accepts the comparison relations too, and the answer is written in the language itself — solve(x^2 - 4 > 0, x) is (x < -2) or (x > 2), and a conjunction such as solve(2*x > 2 and x < 5, x) solves side by side and recombines. Tiers: constant, linear (with the direction flip on a negative coefficient), and a sign chart for every rational function with numeric coefficients, read from its written factors so that roots 10⁻⁸ apart stay apart (critical points are the zeros and the poles; a non-strict relation keeps an isolated zero: solve((x - 1)^2/(x - 2) >= 0, x) is x = 1 or x > 2). A coefficient whose sign cannot be determined leaves the whole relation symbolic — solve(a*x > b, x) is refused rather than solved for one sign of a. Under exact on a rational function with exact coefficients is decided by an exact sign chart: its real roots are counted by a Sturm sequence and isolated with no floating point, so roots 10⁻¹⁰ apart stay two roots, a rational root or a quadratic factor’s surd is an exact bound, and a non-strict relation is answered as well (solve((x - 1)^2/(x - 2) >= 0, x) is x = 1 or x > 2). domain and singularities read their points the same way.

  • Domain analysis: domain(e, v), differentiable(e, v) and singularities(e, v) report where an expression is defined, differentiable, or singular — answered in the language, as comparisons and connectives: domain(ln(x - 2), x) is (x > 2), and singularities(1/(x-1)^2, x) is a location-over-order matrix. Pole orders come from square-free factorisation, not root counting. The analysis deliberately describes what the library computes, not the analytic extension: exclusion sets that are infinite (tan, Gamma) stay symbolic rather than being truncated, and an optional third argument selects the real or complex reading. So domain(x^(2/3), x) is (x >= 0): the library raises a negative base to a fractional power as the principal complex value, not the real root. differentiable excludes a point only where the function is not differentiable there: differentiable(abs(x), x) is x != 0, while differentiable(x*abs(x), x) is true, since the derivative’s limit at 0 is the value the library computes there.

  • Base conversion: the literals 0b1011, 0o17, 0xff and 0t1TT (balanced ternary), plus tobase(n, b) for any radix 2..36 and balanced(n). The base lives on the value, so A := 0xFF still prints 0xFF after a :save/:load round-trip while remaining usable as 255 everywhere; the tag is display-deep only — 0xFF + 1 is decimal 256, since there is no defensible rule for whose base wins in 0xFF + 0b1011.

  • Statistics: Descriptive statistics over samples (mean, variance, stddev, covariance, correlation) that stay exact when the sample is written exactly; least squares via regress(X, y), solved by QR rather than the normal equations so the condition number is never squared — with a ridge form regress(X, y, lambda) and a weighted one wregress(X, y, w), both reduced to the same QR (on [X; √λ·I], and on rows scaled by √wᵢ) so neither squares it either; ridge solves the rank-deficient design ordinary regression declines, and λ = 0 is ordinary regression exactly; order statistics — median, quantile(x, p) (Hyndman–Fan type 7, or the textbook type 6 on request), sort, and bincounts behind the browser’s hist; and an inference tier — ttest for one sample or two (Welch, or pooled), one-sided with less/greater, proptest for one or two proportions, confint, chisqtest for goodness of fit or independence on a table, vartest and one-way anova — so ttest(sample, 5) < 0.05 reads the way statistics is actually written. Every p-value takes its tail directly, never as 1 − cdf, which cancels exactly where it matters. Recursive least squares, rls(theta, P, phi, y, lambda), updates an estimate one observation at a time with a forgetting factor λ ∈ (0, 1]: state in, state out, returned as [[theta', P']] so theta, P := rls(theta, P, phi, y, 0.98) carries it from one update to the next. It is exactly exponentially weighted least squares — at λ = 1 from a large initial P it agrees with regress, and below 1 it tracks a drifting parameter. Several outputs update at once (theta n×m, y m×1), P is symmetrised explicitly each step since floating point lets the triangles drift apart over thousands of updates, exact input stays exact, and a factor outside (0, 1], disagreeing shapes or a non-positive λ + φᵀPφ leave the call unevaluated.

  • Optimization: The symbolic half first — what a numeric library cannot do. stationary(f, x, y) lists every point where the gradient vanishes, solving the nonlinear system by elimination and following the branch where an eliminated coefficient is zero, so no point silently disappears, and — where every equation couples the unknowns — through an exact lexicographic Gröbner basis, whose triangular shape elimination then finishes; the REPL classifies each by the second-order test. On exact input a rational stationary point is answered exactly (x = 1, not x = 1.0); an irrational one comes back at the working precision. convex(f, x, y) proves convexity from every principal minor of the symbolic Hessian, or refutes it with a witness. lagrange handles equality constraints and kkt states the Karush–Kuhn–Tucker conditions in the language. A numeric minimize — gradient descent, Newton, BFGS and a projected BFGS for box constraints, each named explicitly — returns a point only after checking its gradient against the precision, and otherwise says why it declined. qp(H, f, A, b, lb, ub) (and an 8-argument form with equalities) minimises ½ zᵀHz + fᵀz under A z ≤ b and bounds by the Goldfarb–Idnani dual active-set method, for H positive definite, and by a primal active-set method from an exact LP feasible point when H is only semidefinite (an LP included); the answer is KKT-certified, a decline says why (not convex, unbounded, infeasible, …), and a solve names its active constraints. The library form qpSolve returns the active set as a warm start for the next problem. lsqfit is nonlinear least squares — a model fitted to data columns (lsqfit(a*exp(b*t), t, T, Y, [[a], [b]], p0)) or a residual column minimised — by scaled Levenberg–Marquardt over QR, with optional bounds and, on cov, the covariance; it answers only a certified fit and declines one whose parameters are not identifiable. nsolve(F, [[x], [y]], x0) finds a root of a square nonlinear system by a dogleg trust region, certifying every equation against the size of its own terms, and declines a minimum of the residual that is not a root. lp(f, A, b, lb, ub) solves a linear program exactly, by the simplex method over the rationals with Bland’s rule, so infeasibility and unboundedness are proved rather than suspected. nlp(f, [[x], [y]], x0, g, h, sqp | auglag) minimises under nonlinear constraints g ≤ 0, h = 0 and optional bounds, by sequential quadratic programming (a damped-BFGS Hessian, so every subproblem is a qp) or an augmented Lagrangian; either way the answer is a local KKT point certified by a scale-free KKT residual, and the REPL names the binding inequalities with their multipliers. Throughout, an answer that cannot be proved complete is not given: a list of stationary points is read as all of them. Every solver’s size and iteration caps are defaults a program can raise on its Environment (env.withLimit(Limit.MaxQpVariables, 2000)); the REPL keeps them. The same holds for every other package’s budgets: series orders, tabulate/sum lengths, exact factorials, truth tables, matrix sizes, simulation and sampling lengths. The one exception, for programs only, is minimizeDerivativeFree over a Scala callback (pattern search or Nelder–Mead), whose answer is an UncertifiedMinimum by type. See Optimization.

  • Probability: Distributions are first-class values — normal(0, 1), binomial(10, 0.3), poisson(4), geometric(0.2), hypergeometric(20, 7, 12), fdist(3, 10) and friends bind to names like any other value. pdf, cdf, prob and quantile answer numeric questions about them, with every cumulative distribution a closed form rather than a numeric integral. expect and variance carry a linearity rule table, so expect(2*X + 3, X) is rewritten symbolically to 2·E[X] + 3 before anything is computed — and expect(X*Y, X) deliberately stays symbolic, because it needs an independence assumption the language cannot state.

    Bayesian inference comes in the two forms every textbook opens with. bayes(prior, likelihood) applies Bayes’ theorem over a finite set of hypotheses — two rows (or two columns) in, the normalised posterior out in the same shape — and it is exact on exact input, so a posterior of fractions stays a posterior of fractions. posterior(prior, likelihood, data) performs a conjugate update, with the likelihood written as the sampling family whose unknown parameter is left free: posterior(betadist(2, 2), binomial(10, p), 7) evaluates to betadist(9.0, 5.0), an ordinary distribution that pdf, cdf, quantile and expect accept unchanged. Three pairs are in the table — Beta–Binomial, Gamma–Poisson and Normal–Normal with known sigma — and the two families they need, betadist(a, b) and gammadist(k, rate), are distributions in their own right; gammadist is shape–rate, the parameterisation in which the Poisson update is simply additive. Anything outside the table stays symbolic: a general posterior has no closed form and would need numerical integration or sampling, and a confident approximation is exactly what the library declines to return.

    Seeded sampling. draw(dist, n, seed) returns n draws from any distribution as an n×1 column, by inverting its cdf — so every family, discrete or continuous, can be sampled with no sampler of its own. The generator is the library’s own (SplitMix64), never the platform’s, so the same seed gives the same numbers on the JVM and in the browser: bit for bit for the underlying stream, and to rounding for a continuous draw, whose cdf goes through each platform’s own exp. The seed is the state — nothing is remembered between calls — and an optional fourth argument continues a stream: draw(d, 3, s, 5) is draws 6 to 8 of the stream draw(d, 8, s) produces. prbs(order, n, seed) is a maximal-length pseudo-random binary sequence of ±1 for orders 2 to 20, period 2ⁿ − 1 with one more +1 than −1 per period — the excitation signal system identification wants; the seed picks the phase.

  • Precision Control: Configurable display precision for numeric results, kept separate from the exact tier’s working precision — showing five decimals of a value computed to thirty is the normal case, and conflating the two would make raising display precision silently change results.

  • Exact arithmetic mode (exact on): numeric literals become exact rationals, so 0.1 + 0.2 is exactly 3/10 and 1/3 * 3 is exactly 1. Matrices are exact too — det of the 3×3 Hilbert matrix is exactly 1/2160 where floating point reports 4.6E-4, and A * inv(A) is exactly the identity; eye, zeros and ones build exact cells, == compares exact matrices exactly, and solveSystem answers an exact system in fractions, more equations than unknowns included when they agree — and fact loses the 170! ceiling that a Double imposes. Calculus stays exact: an integral’s constants are fractions, a rational function is decomposed over the rationals (an irrational root carried at the working precision, like any irrational in this mode), and a derivative or integral of letters bound to exact values answers in fractions (derive(a/t, t) with a := 1/3, t := 2 is -1/12). Transcendentals are arbitrary-precision, so a user-settable working precision genuinely sharpens sin and exp themselves: exp(1000) is an exact 435-digit value where floating point overflows to infinity. Square roots stay exact: the root of a fraction is a surd a + b√d, shown √13 and typed with √, so a quadratic’s roots (solve(1 - 2k² = 0, k) is ±√2/2), a 2-norm, a standard deviation and a Cholesky factor come back exact, and det, inv, lu and A^n work over a matrix whose surds share one root. Off by default, so the floating-point path is unchanged. A decimal comes back into the exact tier only when asked: rationalize(x[, digits]) replaces every decimal of x (a number, a matrix, a symbolic expression) with its nearest fraction, and declines a complex number or an interval. The REPL offers it in a note when an exact input came back as decimals that all look like small fractions, as lu gives in exact mode.

  • Interval arithmetic: [lo, hi] is a value whose endpoints are rigorous bounds. + − × ÷, powers and exp ln log sin cos tan asin acos atan sinh cosh tanh abs return an interval guaranteed to contain every value they can take, each endpoint rounded outward. Error-free transformations detect an exact Double result, so [1, 2] − [1, 2] is exactly [−1, 1]; transcendentals are widened by two ulps. The cases that are easy to get wrong come out right:
    • [−2, 1]² is [0, 4], not [1, 4];
    • sin([0, π]) is [0, 1], its maximum found inside;
    • a divisor containing zero, or tan across a pole, stays symbolic rather than producing rays.

    Comparisons answer unknown when the ranges overlap. In exact mode the endpoints are exact rationals, bounded through arbitrary-precision arithmetic. An interval is never read as a single number, so every operation without an interval rule simply stays symbolic.

  • LaTeX output (latex on): every result also comes back as LaTeX source. The substance is a precedence pass, not a transcription: toString parenthesises defensively because it must re-parse, while \frac, \sqrt and ^{…} carry their own grouping, so (a+b)/(c+d) renders as \frac{a + b}{c + d} with both pairs of parentheses gone — and a power under a power is re-bracketed, because x^{2}^{3} is not ugly, it is a LaTeX double-superscript error. The notation rules cover radicals (recognised from all three ways a fractional exponent can arrive), exact rationals kept as fractions, pmatrix, the binders (\int … \,dx, \frac{d}{dx}, \lim_{x \to a}, \mathcal{L}\{f\}(s)), Greek names and LaTeX’s own operator macros — \sin, not \mathrm{sin}, because the macro carries the spacing that tells a reader a function from a product of three letters. Anything without a rule degrades to \mathrm{…} of its ordinary spelling, so the emitter is plain where it is incomplete and never wrong. The printed answer does not change: the LaTeX travels on a second channel, because a terminal cannot typeset and would be left showing markup where a result belongs. The browser REPL reads that channel and typesets the formula beside the answer with the vendored MathLive, whose full build also carries the page’s math editor.

  • MCP server: leonardo-mcp serves the REPL to an AI assistant over the Model Context Protocol (stdio), so the assistant delegates symbolic, exact and certified numeric work to Leonardo instead of computing in-model. Typed tools for simplify, derive, integrate, solve and limit beside a general evaluate, one session per server whose state persists between calls, a result’s LaTeX as a second part, and a result as Scala source on request. A request has a time limit; a timed-out one is answered at once and the session goes on. It reaches no file and cannot end the process. A runnable jar on every Release, or cs launch from Maven Central; JDK 25. See MCP server.

  • Normalization: normalize(e, x) collects like terms into an ascending polynomial in one variable (10x - 2x → 8x, whatever the tree shape), and collect(e, x) extracts the dense coefficient list — the polynomial prerequisite the equation solver, the integration tiers and the transforms are all built on. Non-polynomial forms are left untouched.

  • Linear system solver: solveSystem([[eq₁, eq₂, …]], x, y, …) (or a column [[eq₁], [eq₂]]) solves a system of linear equations, as many as or more than the unknowns: a consistent over-determined system — is b a combination of these vectors? — is solved, and an inconsistent one stays unevaluated while the REPL names the equation at fault. Coefficient extraction uses collect (the same polynomial prerequisite as solve). Exact path: when every coefficient is an exact rational (exact on), elimination over the rationals, so the answer is in fractions. Over-determined numeric systems go through QR least squares and are accepted only when every equation holds against its own terms. Dense path: Gaussian elimination with partial pivoting on Double arrays, declining a singular or near-singular system — judged relative to the matrix’s own scale, so a change of units cannot change the verdict. Symbolic path: row reduction using _Expression arithmetic and simplifyFully when any coefficient or constant stays symbolic. Named equation matrices work too: S := [[eq1, eq2]]; solveSystem(S, x, y). Solutions display as [[x = 2.0, y = 1.0]].

  • Clean API: Environment-aware evaluation with no implicit global state. Expressions are immutable and composable. Environment is immutable — withBinding returns a new instance, enabling safe concurrent evaluation.

  • Performance: Rounding is deferred to display time only (no mid-computation precision loss). Every AST node caches its free-variable set (freeVars) after the first traversal, making dependsOn O(1). Definite-integral evaluation (Simpson’s rule) uses a compiled Double => Double closure when the integrand has no unresolvable symbolic nodes, eliminating per-step allocations. The same table compiles an expression over several variables (compile(e, vars, env), a closure over an Array[Double]) and a matrix cell by cell (compileMatrix), for code that evaluates a model or a Jacobian thousands of times: measured 7–10× faster than eval on a 3×3 Jacobian. derive and simplify are memoized behind bounded thread-safe caches — repeated derivatives of the same tree (e.g. Simpson’s-rule fallback sampling) and simplifyFully’s fixpoint passes are paid once.

This site uses Just the Docs, a documentation theme for Jekyll.