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 constantspi,e,eulergamma,goldenratio(with the glyphsπ,γ,φ) andi(imaginary unit). The named constants are symbols: a formula keepspi, exact mode answerssin(pi/6)as1/2, and outside exact mode each evaluates to itsDouble. Logarithms:ln(x)is the natural log;log(x)is decimal (base-10);log(x, b)is the general base-b log computed asln(x)/ln(b)— solog(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
- A numeric result (
-
Complex Numbers: The imaginary unit
iis a built-in constant (2 + 3i,3i), sitting alongsidepiande. 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 functionsexp,ln,log,sin,cos,tanaccept 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)(orbi/iwhen purely imaginary) and round-trip through the parser; a floating-point residual imaginary part rounds away at display, soexp(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, withsimplifynormalising 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) andmod(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 anddifferentiableexcludes them; a definite integral of a staircase of a linear argument is split at its jumps (integral(floor(x), x, 0, 3)is3, exact on exact input); a two-sidedlimitat 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/cotpowers), full rational-function partial fractions (repeated and complex roots at any degree, via square-free factorisation), non-linear u-substitution forf(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 substitutiont = tan(x/2)for rational functions ofsin/cos(∫ 1/(1+sin x),∫ 1/(2+cos x)), the special integral functionsSi/Ci/Ei/li/fresnelS/fresnelCas 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 generale^(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)·gby parts, odd powers ofsin/cos,u = ax + b,w = x²,x = u^qfor fractional powers,x = eᵘforf(ln x)— sox·√(1 − x),sin⁵x·cos⁸x,√x/(x² + x)andcos(ln x)close, and limits)
-
Matrix Domain: matrix literals parse as
[[1, 2], [3, 4]](a row vector is[[1, 2]]), withtranspose(...),det(...),inv(...), and the ordinary+,-,*,/operators —M := [[1, 2], [3, 4]]thenM * Mworks 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-majorArray[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 spelling1 / Areturn the inverse matrix (M / NisM · N⁻¹), staying symbolic whenAis 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 asf(cell)until they are bound. A square dense matrix can be raised to an integer power with the ordinary^operator orpow(A, n):A^0is the identity,A^nmultipliesAby 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]](sor, c := size(A)names both) andsize(A, 1)/size(A, 2)one dimension, in the operand’s tier; a number is1×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 thaneigen(AᵀA)), and1,inf,froand, for a vector, anyp ≥ 1. All four stay exact on exact cells and build a symbolic answer from symbolic ones where one exists; aDouble2-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 tonorm(x). -
Matrix exponential:
expm(A)computes the matrix exponentiale^A = Σ Aᵏ/k!— a different operation fromA^n, which is repeated multiplication. It uses scaling and squaring with a degree-13 Padé approximant, resting on the identitye^A = (e^(A/2ˢ))^(2ˢ):Ais 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-formexpm([[λ,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, somaximum(u, 0)rectifies a whole column.max(v)/min(v)reduce one array to its extreme entry, over every entry whatever the shape (themean(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 — andsoftplus(x, k) = ln(1 + e^(k·x))/kis the smoothmaximum(0, x), evaluated as(max(k·x, 0) + log1p(e^(−|k·x|)))/kso that a largek·xdoes 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 isorunder min–max but not under theproductorlukasiewiczsemantics, 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)is1at0— the textbookstep(a−b)·a' + step(b−a)·b'would give3there, outside the subgradient[1, 2].differentiablereports each kink as an excluded point, and the same correction reached the step itself:differentiable(step(x), x)is nowx ≠ 0, where it used to answerfalse. -
Block matrices:
hcat(A, B, …)andvcat(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, andsubmatrix(A, r0, r1, c0, c1)slices rowsr0..r1and columnsc0..c1— 1-based and inclusive, the conventionat(A, i, j)already uses, so the1×1slice holds exactlyat(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 — ablkdiag’s zero blocks are built exact beside exact blocks) and a symbolic one. A number counts as a1×1block inhcat,vcat,blkdiagandkron, the MATLAB reading; a free name is never guessed to be one, since it may later be bound to a matrix, sohcat(x, A)waits untilxis 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).subwas deliberately not reserved — too plausible a variable name — hencesubmatrix. For model-predictive control,mpcMatrices(A, B, C, Np, Nc)builds the prediction matrices[[Φ, Γ]]ofY = Φ·x + Γ·Ufrom 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-triangularLwith a positive diagonal andA = L·Lᵀfor a symmetric positive-definiteA—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 makescholthe 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, soAand10⁶·Aalways 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 ofLcarries a single root, soL·Lᵀgives backAexactly. -
Singular values:
svd(A)returns[[U, S, V]]withA = U·S·Vᵀ, the singular values onS’s diagonal largest first — the economy form by default (Um×k,Sk×k,Vn×k,k = min(m, n)), andsvd(A, full)for square orthogonalUandVwhose extra columns span the null spaces. The kernel is one-sided Jacobi, which never formsAᵀAand so never squares the condition number, and it is certified — a decomposition that does not reconstructAwith orthonormal factors stays unevaluated. Three answers read off it:rank(A)(orrank(A, tol)),pinv(A)the Moore–Penrose pseudo-inverse, andcond(A)the 2-norm condition number,inffor a singular matrix; and two orthonormal bases,nullspace(A)andorth(A)for the null space and the range,falsewhen the subspace is trivial.rank,pinv,nullspaceandorthshare one definition of numerically zero,σ ≤ 0.5·10⁻ᵖ·σ_maxat session precisionp— relative to the largest singular value, soAand10⁹·Aalways have the same rank — whilecondreports finite values right up to the rounding floor, since its job is to say how near singular a matrix is. Exact input is decomposed inDouble, asqris (luis exact on exact input); the work is capped atmax(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 + 1parses as a relation; once all variables are bound, it evaluates totrue/falseusing tolerance-based equality tied to the configured precision (sosin(pi) = 0is 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, andintegrateapply to both sides. Equations are first-class values:h := x^2 = 4stores the relation, andsolve(h, x)then works.lhs == rhsis an explicit equality check (same semantics, but not accepted bysolve()).solve(lhs = rhs, x)— or equivalentlysolve(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 asx = 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 (herex = 3); an inconsistent system such as[[x, x]] = [[1, 2]]has no solution and stays symbolic. The unknown may also be a matrix: withAandBbound,solve(A * X = B, X)returns the uniqueX = A⁻¹·Bvia the inverse kernel (singular or non-conformingA→ no solution);solve(X * A = B, X)givesX = 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 whereXappears in several terms — the Sylvester equationsolve(A * X + X * B = C, X), the Lyapunov equationsolve(A * X + X * transpose(A) = C, X), scalar coefficientssolve(2 * X = B, X)— are solved by Kronecker vectorization: each terms·L·X·Rcontributess·(Rᵀ ⊗ L)to a dense linear system overvec(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.Aand−Bsharing an eigenvalue — has no solution). -
Logic: the word connectives
and,or,not,implies,xor,iffoperate on the boolean literalstrue/falseand on anything that reduces to a boolean — equations included, sox = 1 and y = 2is a conjunction of two relations. Connectives bind looser than=/==, with precedencenot>and>xor>or>implies>iff(impliesright-associative,iffnot chaining).and/or/impliesshort-circuit on a decisive left operand (false and Xisfalsewithout evaluatingX), 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 band De Morgan where it removes a negation (all but De Morgan gated on crisp operands);toCNF/toDNFproduce conjunctive/disjunctive normal forms (De Morgan plus distribution, capped against exponential blow-up), at the promptcnf(e)/dnf(e), and the REPL’struth <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); underpretty ona 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.unknownis a first-class value (bindable, printable, restored by:save) sitting at degree 0.5:not unknownisunknown(its negation fixpoint), while the crisp cases still decide (false and unknownisfalse,true or unknownistrue) — 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 atunknown(complementa 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 offalse/unknown/true, related by the affine mapt = (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 0is-1,1 or 0is1,not 0is0). Switched perEnvironment(logic symmetric onat the REPL, persisted by:save), which means a bound variable participates too, not just literals. With the toggle off a bare0stays a plain number so nothing is silently reinterpreted, and ordinary arithmetic is untouched in both modes. Under the encoding the digit0counts as graded, so0 and not 0correctly stays0rather 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 hedgesvery(d) = d²/somewhat(d) = √dmap crisp measurements into degrees. They evaluate to truth values, sovery(trimf(t, 0, 10, 20)) and somewhat(h)composes with no cast at each step. Which t-norm combines degrees is anEnvironmentparameter 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 argumentmomorbisectorby 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 to170!and continues analytically past them (fact(0.5)is√pi/2);dfact(n)is the double factorial andmfact(n, k)the multifactorial with stepk.Gamma(z)is the Lanczos approximation with the reflection formula for negative arguments,lgamma(z)its log-space companion that stays finite whereGammaitself overflows, andBeta(a, b)the beta function computed throughlgammaso large arguments survive.GammaandBetaare capitalised deliberately, so the lowercasegammaandbetastay available as ordinary variable names. The analytic tier extends the family with the error functionerf/erfc, the digamma function (which is what makesGammaandfactdifferentiable), the regularised incomplete gamma (gammaP/gammaQ) and incomplete beta (betaI), andGammaover 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 withlucas,pellandjacobsthal, all one recurrencex(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)andfib(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 asfib(n, 1, 1), which is the same sequence shifted by one. They are numeric, not integer, sequences: a recurrence needs only addition and multiplication, sofib(5, 1.5, -pi)is a legitimate call and exact seeds stay exact. That last point is not decoration — aDoublestops representing Fibonacci numbers exactly atfib(78), so in exact modefib(100)is354224848179261915075rather than an approximation (Binet’s formula is deliberately not used: elegant, but inexact pastn ≈ 70). Alongside them:binom(generalised to a real upper index, sobinom(-1, 3) = -1),catalan, andharmonic, which is rational-valued and shows the exact tier off nicely —harmonic(4)is25/12. Finallytabulate(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:saveall work on it unchanged — withsum(e, k, lo, hi)andproduct(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)is11/6), symbolic terms expand sosimplifycan collect them (sum(k*x, k, 1, 3)becomes6x), and an empty range gives the operator’s identity —0and1— sosum(f, k, 1, n)reads correctly atn = 0instead 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), plusjacobian(F, ...)andhessian(f, ...). A vector field is simply an n×1 matrix —div([[x^2], [y^3]], x, y)gives2x + 3y^2, andcurl([[-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: acurloutside 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)is0, anddiv([[1/r], [0], [0]], r, t, z, cylindrical)is0, 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:sphericalis the physics order(r, θ, φ)withθthe polar angle, andsphericalmathsthe mathematics order withθazimuthal andφpolar. Exchanging those two coordinates flips the handedness of the basis, socurl— 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, sointegral(integral(x*y, y, 0, x), x, 0, 1)is0.125. -
Series Expansions:
taylor(e, v, point, n)expands an expression as a truncated Taylor polynomial about a point, andmaclaurin(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/coshby 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, andtaylor(tan(x), x, 0, 20)is instant. A quotient that vanishes into0/0at the centre is cancelled first, somaclaurin(sin(x)/x, x, 6)is1 - x^2/6 + x^4/120 - x^6/5040andmaclaurin(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 (laurentis 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 symbolicayields a genuine polynomial in(x − a)withf⁽ᵏ⁾(a)coefficients. The expansion variable stays free in the result, so binding it evaluates the polynomial and the series composes withderive,samplesand the rest of the library. Order is capped at 20. A function the arithmetic does not cover (erfand the other special functions) is differentiated instead, and only that subexpression: its derivatives are held to 50 000 nodes, sotaylor(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, andtaylor,laurentandpadeall 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 seriesa0/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 forintegral(f, x, a, b), so the period must be a concrete positive number. The classic results come out as expected — the sawtoothfourierSeries(x, x, 2*pi, 4)gives2sin(x) - sin(2x) + (2/3)sin(3x) - (1/2)sin(4x), andx^2gives a cosine-only series with constant termpi²/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 withfourier(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 lengthmis optional: omitted, it is detected from the pole order reported bysingularities. 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 quotientP/Qwithdeg P <= m,deg Q <= nandQ(0) = 1whose Maclaurin series matches the function through orderm + 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), andpade(exp(x), x, 2, 2)beatsmaclaurin(exp(x), x, 4)atx = 1. A rational function reproduces itself exactly, andpade(f, x, m, 0)degenerates to the Taylor polynomial. The defining linear system is solved through the dense matrix inverse incore; 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)forGamma(z)andβ(x, y)forBeta(x, y)— and the REPL can insert the glyphs with anALT-\prefix (ALT-\ g,ALT-\ b;ALT-Galso works directly). A prefix was chosen over one chord per symbol becauseALT-Bis alreadybackward-wordin 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 LatinB, 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 andtoStringalways 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 — solimit(n/2^n, n, inf),limit((1 + 2/x)^x, x, inf),limit(ln(t), t, 0, +)andlimit(((x + h)^2 - x^2)/h, h, 0)answer, the last as2x. With a free parameter the answer is generic and the REPL notes what it assumed (limit(x/(x - a), x, 2): assuming2 - 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.infis a built-in constant equal to+∞;-inffollows 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 theoreme^(at)·g(t) → G(s−a)applied recursively — solaplace(t*exp(-t), t, s)yields1/(s+1)².fourier(f, t, w)is the two-sided Fourier transform,∫ f(t)·e^(−iwt) dtover the whole line, computed as the Laplace transforms of the causal part and of the reflected anti-causal part ats = ±i·w— sofourier(exp(-abs(t)), t, w)is2/(1 + w²)and the centred pulsestep(t+1) − step(t−1)gives2·sin(w)/w;fourierCausal(f, t, w)is the transform off(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.1andcos(t)would need Dirac deltas, which the library has no node for, andexp(-t)diverges ast → −∞, 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-transformX(z) = Σ(n≥0) x[n]·z⁻ⁿ, the discrete counterpart oflaplaceand 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 notc/z— the Laplace analogueL{c} = c/sdoes not carry over, since a constant sequence iscat every index. Then-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 decomposingX(z)/z— the division is the technique, since every forward entry carries a factor ofzin its numerator — with eachz/(z−r)^jterm inverting toC(n, j−1)·r^(n−j+1), so distinct and repeated real poles both work:invztrans(z/((z-1)*(z-2)), z, n)is2ⁿ − 1andinvztrans(z/(z-2)^2, z, n)isn·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)andidft(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 isztransevaluated atz = 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 giveb/(s−a) → b·e^(at), distinct real roots split via partial fractions intoA·e^(r₁t) + B·e^(r₂t), a repeated root givese^(at)·(N₁ + (N₀+N₁a)·t), and a complex-conjugate pair givese^(at)·(N₁cos(wt) + …sin(wt)). Soinvlaplace(3/((s-2)^2+9), s, t)returnse^(2t)·sin(3t), andinvlaplace(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), neverg.poles). Interconnection:series(G, H, s),parallel(G, H, s)andfeedback(G, H, s), each returning one rational in lowest terms —feedback(1/(s*(s+2)), 1, s)is1/(s²+2s+1), not the uncancelled quartic whose spurious roots at0and−2would be reported as poles.feedbackis negative feedback, stated because it cannot be inferred: a substantial part of the literature writesG/(1 − G·H), and choosing silently would make every closed-loop answer wrong for half its readers. Time responsestep(G, s, t)andimpulse(G, s, t)are the inverse Laplace transform ofG/sandG;stepis arity-overloaded, sostep(x)remains the Heaviside unit step.poles/zerosreturn_Values rather thanDoubles 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.isStabledecides 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 —routhTableis still there for inspection) and is strict, so marginal stability is not stability. At the prompt the poles and zeros aretfpoles(G, s)/tfzeros(G, s)—zeros(r, c)is already the zero matrix — besiderouthTable(G, s)(the array as a padded matrix),controllable/observableand the matricesctrb/obsv, single-input pole placementacker(A, B, poles)(Ackermann’s formula, certified by the eigenvalues it places), the browser’srlocusroot locus (closed-loop poles over a gain band, matched into continuous branches),isStable,isStableDiscrete,stateSpaceandc2d(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 statesx[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;dlqradds the gain of the lawu = −K·xand provesA − B·Kstable,dlyapsolves the Stein equationA·X·Aᵀ − X + Q = 0, andkalmanGain/kalmanStepare 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Δuformulations, 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/nyquistare one substitutions → iωriding the existing complex closure, andfrequencyResponse/nyquistSweepare their swept forms — the two things a diagram needs that a plainsamplecannot give it. The grid is geometric, because a response is read across decades and a linear grid of 200 points over0.01 .. 100puts 199 in the last decade and none near a corner at0.1. The phase is unwrapped:atan2’s principal value is(−π, π], so a raw sweep of1/(s+1)^3reports+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 frombode. 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 the1×4matrix rowlu/qr/eigalready return, withcontrollable/observable— the second defined as the first on the dual pair, so they cannot disagree. A nonlinear model reaches it throughlinearize(F, G, x, u, x0, u0), the four Jacobians at an operating point with the state and input tuples ordered and explicit, andaffineappending the offsetsF(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)fitsy[k] = Σ aᵢ·y[k−i] + Σ bₗ·u[k−nk−l+1]by least squares for several inputs at once, in the predictor sign (MATLAB’sais 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)andarx2ss(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×pblocksAᵢ, returned stacked), whose transfer matrix isA(z)⁻¹B(z)and whose realisation is the block observer form, non-minimal and stated. Discretisationc2d/d2calways names its method (ZohorTustin), never defaults silently, since the two give different discrete poles;c2dExactuses the matrix exponential of[[A, B], [0, 0]]·Tsrather thanA⁻¹(A_d − I)B, which is a correctness matter because the block form is defined for a singularAand any system with an integrator has one. Declined rather than approximated: a non-rationalGsuch as a dead-timeexp(−2s)(padeexists, and reaching for it is the user’s choice), an improperGin a time response (the impulsive term att = 0is not representable), an undeterminable coefficient sign, andd2cby zero-order hold. -
Differential Equations:
ode(rhs, y, t, t0, y0, target)solves the first-order initial-value problemy' = rhs(t, y),y(t₀) = y₀, and returns the solution valuey(target). Linear equationsy' = a(t)·y + b(t)are solved in closed form: constant coefficients directly (y' = y, y(0)=1giveseexactly att = 1;y' = 2y + 3gives 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 liket·eᵗcloses by integration by parts). A freetarget, 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 whentarget < t₀); a non-evaluable right-hand side or a symbolic target with no closed form stays symbolic. Linear systems use the sameode: wheny0is ann×1column and the right-hand side isA*y,A*y + borb + A*ywith a constant square matrixAand columnb, the answer is the state vectore^(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 kernelc2dExactuses — rather than through eigenvectors, so a defectiveAsuch as the double integrator[[0, 1], [0, 0]]and a singularAwith a constant input both come out right where the eigen route andA⁻¹(Φ − I)bwould 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 throughat(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 isode([[x - x*y], [x*y - y]], [[x], [y]], t, 0, [[2], [1]], 5). The answer is certified by step doubling: RK4 runs withnand2nsteps 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 aftert0, andodeSolve(F, y, t, t0, y0, t1, h, method)the trajectory, one row[t, state…]per output time witht1always the last.eulerandrk4take exactly one uncertified step of sizeh— the step is the caller’s, which is what a controller simulation wants — whilerk45is adaptive Dormand–Prince,hthen 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 withand/or/not/implies, sox > 0 and x < 10is 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 == 2istrueand 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:
solveaccepts 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 assolve(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 roots10⁻⁸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)isx = 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 ofa. Underexact ona 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 roots10⁻¹⁰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)isx = 1 or x > 2).domainandsingularitiesread their points the same way. -
Domain analysis:
domain(e, v),differentiable(e, v)andsingularities(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), andsingularities(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. Sodomain(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.differentiableexcludes a point only where the function is not differentiable there:differentiable(abs(x), x)isx != 0, whiledifferentiable(x*abs(x), x)istrue, since the derivative’s limit at0is the value the library computes there. -
Base conversion: the literals
0b1011,0o17,0xffand0t1TT(balanced ternary), plustobase(n, b)for any radix 2..36 andbalanced(n). The base lives on the value, soA := 0xFFstill prints0xFFafter a:save/:loadround-trip while remaining usable as255everywhere; the tag is display-deep only —0xFF + 1is decimal256, since there is no defensible rule for whose base wins in0xFF + 0b1011. -
Statistics: Descriptive statistics over samples (
mean,variance,stddev,covariance,correlation) that stay exact when the sample is written exactly; least squares viaregress(X, y), solved by QR rather than the normal equations so the condition number is never squared — with a ridge formregress(X, y, lambda)and a weighted onewregress(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λ = 0is ordinary regression exactly; order statistics —median,quantile(x, p)(Hyndman–Fan type 7, or the textbook type 6 on request),sort, andbincountsbehind the browser’shist; and an inference tier —ttestfor one sample or two (Welch, orpooled), one-sided withless/greater,proptestfor one or two proportions,confint,chisqtestfor goodness of fit or independence on a table,vartestand one-wayanova— sottest(sample, 5) < 0.05reads the way statistics is actually written. Every p-value takes its tail directly, never as1 − 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']]sotheta, P := rls(theta, P, phi, y, 0.98)carries it from one update to the next. It is exactly exponentially weighted least squares — atλ = 1from a large initialPit agrees withregress, and below 1 it tracks a drifting parameter. Several outputs update at once (thetan×m,ym×1),Pis 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, notx = 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.lagrangehandles equality constraints andkktstates the Karush–Kuhn–Tucker conditions in the language. A numericminimize— 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ᵀzunderA z ≤ band bounds by the Goldfarb–Idnani dual active-set method, forHpositive definite, and by a primal active-set method from an exact LP feasible point whenHis 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 formqpSolvereturns the active set as a warm start for the next problem.lsqfitis 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, oncov, 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 constraintsg ≤ 0,h = 0and optional bounds, by sequential quadratic programming (a damped-BFGS Hessian, so every subproblem is aqp) 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 itsEnvironment(env.withLimit(Limit.MaxQpVariables, 2000)); the REPL keeps them. The same holds for every other package’s budgets: series orders,tabulate/sumlengths, exact factorials, truth tables, matrix sizes, simulation and sampling lengths. The one exception, for programs only, isminimizeDerivativeFreeover a Scala callback (pattern search or Nelder–Mead), whose answer is anUncertifiedMinimumby 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,probandquantileanswer numeric questions about them, with every cumulative distribution a closed form rather than a numeric integral.expectandvariancecarry a linearity rule table, soexpect(2*X + 3, X)is rewritten symbolically to2·E[X] + 3before anything is computed — andexpect(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 tobetadist(9.0, 5.0), an ordinary distribution thatpdf,cdf,quantileandexpectaccept unchanged. Three pairs are in the table — Beta–Binomial, Gamma–Poisson and Normal–Normal with knownsigma— and the two families they need,betadist(a, b)andgammadist(k, rate), are distributions in their own right;gammadistis 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)returnsndraws from any distribution as ann×1column, 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 ownexp. 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 streamdraw(d, 8, s)produces.prbs(order, n, seed)is a maximal-length pseudo-random binary sequence of±1for orders 2 to 20, period2ⁿ − 1with one more+1than−1per 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, so0.1 + 0.2is exactly3/10and1/3 * 3is exactly1. Matrices are exact too —detof the 3×3 Hilbert matrix is exactly1/2160where floating point reports4.6E-4, andA * inv(A)is exactly the identity;eye,zerosandonesbuild exact cells,==compares exact matrices exactly, andsolveSystemanswers an exact system in fractions, more equations than unknowns included when they agree — andfactloses the170!ceiling that aDoubleimposes. 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)witha := 1/3,t := 2is-1/12). Transcendentals are arbitrary-precision, so a user-settable working precision genuinely sharpenssinandexpthemselves: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 surda + b√d, shown√13and 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, anddet,inv,luandA^nwork 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 ofx(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, aslugives in exact mode. - Interval arithmetic:
[lo, hi]is a value whose endpoints are rigorous bounds.+ − × ÷, powers andexp ln log sin cos tan asin acos atan sinh cosh tanh absreturn an interval guaranteed to contain every value they can take, each endpoint rounded outward. Error-free transformations detect an exactDoubleresult, 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
tanacross a pole, stays symbolic rather than producing rays.
Comparisons answer
unknownwhen 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:toStringparenthesises defensively because it must re-parse, while\frac,\sqrtand^{…}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, becausex^{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-mcpserves 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 forsimplify,derive,integrate,solveandlimitbeside a generalevaluate, 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, orcs launchfrom 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), andcollect(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 — isba combination of these vectors? — is solved, and an inconsistent one stays unevaluated while the REPL names the equation at fault. Coefficient extraction usescollect(the same polynomial prerequisite assolve). 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_Expressionarithmetic andsimplifyFullywhen 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.
Environmentis immutable —withBindingreturns 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, makingdependsOnO(1). Definite-integral evaluation (Simpson’s rule) uses a compiledDouble => Doubleclosure 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 anArray[Double]) and a matrix cell by cell (compileMatrix), for code that evaluates a model or a Jacobian thousands of times: measured 7–10× faster thanevalon a 3×3 Jacobian.deriveandsimplifyare memoized behind bounded thread-safe caches — repeated derivatives of the same tree (e.g. Simpson’s-rule fallback sampling) andsimplifyFully’s fixpoint passes are paid once.