mathr — Rust Math Library, CLI Calculator & Web Notebook
mathr is a pure-Rust mathematics library and command-line calculator for symbolic and numerical computation — built from scratch with zero external math dependencies. It includes a Jupyter-like web notebook with KaTeX math rendering, step-by-step solving, and exact fraction arithmetic.
Table of Contents
- Features
- Quick Start
- CLI Usage
- LaTeX / TeX Input
- REPL
- Web Notebook
- Crate API
- Modules
- Dependencies
- License
Features
Symbolic Computation
- Symbolic differentiation — product, quotient, chain rules; partial derivatives and gradients
- Symbolic integration — polynomial, exponential, trigonometric, and inverse-trigonometric primitives
- Algebraic simplification — constant folding and algebraic identity simplification
- Taylor series — symbolic expansion around any point
- Laurent series — expansion around poles with negative powers
- Exact rational arithmetic —
Rationaltype with GCD reduction; expressions with integer fractions evaluate exactly (e.g.\frac{1}{2} + \frac{3}{4}→5/4)
Numerical Computation
- Numerical calculus — high-order finite-difference derivatives, trapezoidal / Simpson's / adaptive quadrature, Romberg with Richardson extrapolation
- FFT — Cooley–Tukey radix-2: forward, inverse, 2D, real-input, magnitude / power spectra, convolution, cross-correlation, window functions (Hann, Hamming, Blackman, Rectangular)
- Equation solving — bisection, Newton–Raphson, secant, Durand–Kerner polynomial roots, Newton's method for nonlinear systems, VAS root isolation
- ODE solvers — Euler, RK4, RK4 systems, adaptive RKF45
- Monte Carlo integration — 1-D and N-D with reproducible LCG and standard error
- Fourier series — numerical coefficient computation via Simpson's rule
Linear Algebra
- Matrix operations — arithmetic, determinant, inverse, linear-system solver, trace, transpose, rank
- LU decomposition with partial pivoting
- Cholesky decomposition
A = L·Lᵀfor SPD matrices - SVD
A = U · Σ · Vᵀvia one-sided Jacobi rotations - Eigenvalue solvers — power iteration, symmetric QR algorithm (Householder + Wilkinson shift)
- Hessenberg and real Schur decomposition
- Tikhonov regularisation for ill-conditioned and rectangular systems
Number Theory
- GCD, LCM, primality (trial + Miller–Rabin), factorization, sieve of Eratosthenes
- Binomial coefficients, factorial, Fibonacci (fast doubling), Euler's totient
- Chinese Remainder Theorem, modular exponentiation, modular inverse
- Jacobi symbol, continued fractions, linear Diophantine solver, discrete logarithm (baby-step giant-step)
- Big integers — arbitrary-precision primality, factorization (Pollard's rho), factorial, Fibonacci, binomial, modular exponentiation, totient via
num-bigint. REPL commandsfact,fib,binomauto-upgrade to BigInt on overflow (no separate "big" command needed for these) - Automatic differentiation — dual numbers for exact forward-mode AD; derivatives, gradients, and Jacobians of arbitrary compositions
- MathML — W3C Presentation MathML export and import for interchange with Word, web browsers, and other CAS systems. Notebook supports MathML cells (input is MathML, imported to Expr and evaluated). Web UI has a "Show MathML" toggle to display MathML output alongside KaTeX rendering.
- Expression serialization — convert
Exprto and from three interchangeable textual formats: S-expressions ((add (mul (num 2) (var x)) (num 1))), JSON ({"t":"add",...}), and RPN (2 x * 1 +). All round-trip viaExpr::equals. Useful for persistence, interop, and pipe-friendly shell workflows.serialize <fmt> <expr>andserialize <fmt> import <text>REPL commands. - Interval arithmetic — rigorous bounds on computations over the
ExprAST. Assign variables to intervals[lo, hi]and get guaranteed bounds on the result. Tracks extrema for trig functions, handles zero-crossings for even powers, and supports the full elementary function set.interval <expr> with <var>=[lo,hi],...REPL command. Pure Rust, no deps. - Arbitrary-precision decimals — evaluate expressions to N significant digits (up to 1000) with correctly-rounded results: π (Machin), e, sqrt, exp, ln, log, trig, and powers, all with 10 guard digits and argument reduction.
dec <expr> [prec <n>] [with <var>=<val>,...]REPL command;bigdecmodule for library use. - Symbolic limits —
lim x→a f(x)for finite points and ±∞ via direct substitution, L'Hôpital's rule (recursive, for 0/0 and ∞/∞), and numeric probing with pole/divergence detection.limit <expr> [<var>] <point>REPL command with step-by-step output in the notebook. - Polynomial expansion —
expand (x+1)^3 → x^3 + 3*x^2 + 3*x + 1: distributes products and integer powers into collected multivariate polynomials; non-polynomial factors stay intact.expandREPL command;poly::to_poly/poly_to_exprfor library use. - Partial fractions — SymPy-style
apart: decomposes rational functions into a quotient plus fractions over linear and irreducible quadratic denominators (numeric factorization + linear solve).apart <expr> [<var>]REPL command with step-by-step output in the notebook. - Condition number & nullspace —
cond <rows>gives the 2-norm condition number from the SVD (singular matrices reportinf);null <rows>returns an orthonormal basis of{x : A·x = 0}via the eigendecomposition ofAᵀA(works for wide matrices).Matrix::condition_number/Matrix::nullspacefor library use.
Interpolation & Special Functions
- Interpolation — Lagrange, Newton, linear, cubic spline, Chebyshev polynomials and series, Legendre polynomials, Gauss–Legendre quadrature
- Special functions — Gamma, log-Gamma, Beta, erf, erfc, sinc, incomplete gamma P, Bessel functions
J_0,J_1,J_n, digamma/trigamma/polygamma, harmonic numbers, Riemann & Hurwitz zeta, elliptic integrals K, E, F(φ,k), E(φ,k) - Fast math — Chebyshev-based approximations of
sin,cos,tan,exp,log,sqrt,powwith argument reduction (~1e-12 accuracy)
Input & Output
- LaTeX / TeX input — parse
\frac,\sqrt,\sin,\pi,\left(\right),^{...},\Gamma,\log_2, and more; supports$...$,$$...$$,\[...\],\(...\)delimiters - Interactive REPL — rustyline-powered with history, variable/function bindings
- Expression parser — recursive-descent, implicit multiplication, scientific notation, 30+ built-in functions
- PNG plotting — line, multi-series, scatter via
plotters - Web notebook — Jupyter-like UI with KaTeX math rendering, step-by-step solving, exact fraction arithmetic,
.mnbfile format, cell-based evaluation
Quick Start
Or build from source:
CLI Usage
Just pass a string — mathr figures out what to do:
# Matrix operations (rows separated by `|`)
# Interpolation
# Number theory
# Special functions
# Plot to PNG
|
# Web notebook (Jupyter-like UI)
LaTeX / TeX Input
mathr accepts LaTeX math formulas — with or without Markdown delimiters:
Supported delimiters: $...$, $$...$$, \[...\], \(...\), or raw TeX with no delimiters.
Supported TeX commands: \frac, \sqrt, \pi, \tau, \infty, \cdot, \times, \left(, \right), ^{...}, \sin, \cos, \tan, \arcsin, \arccos, \arctan, \sinh, \cosh, \tanh, \exp, \ln, \log, \log_2, \log_{10}, \Gamma, \operatorname{...}, \text{...}.
REPL
The interactive REPL supports variable bindings, function definitions, and all commands:
mathr> sin(pi/4)
0.7071067812
mathr> let x = 3
mathr> x^2 + 1
10
mathr> fn f(x) = x^2 + 2*x + 1
mathr> f(5)
36
mathr> diff sin(x^2)
2*x*cos(x^2)
mathr> integrate sin(x)
-cos(x)
mathr> taylor exp(x) 0 5
1 + x + 0.5*x^2 + 0.1666666667*x^3 + 0.0416666667*x^4
mathr> romberg sin(x) 0 3.14159
2
mathr> svd 1 2 | 3 4 | 5 6
σ = [9.525518, 0.514301]
mathr> det 1 2 | 3 4
det = -2
mathr> fast sin 1.5
fast sin(1.5) = 0.997495 (exact: 0.997495, err: 0e0)
mathr> big prime 1000000007
1000000007 is prime
mathr> big fact 25
25! = 15511210043330985984000000
mathr> big fib 100
F_100 = 354224848179261915075
mathr> fact 25
15511210043330985984000000
mathr> fib 100
354224848179261915075
mathr> binom 100 50
100891344545564193334812497256
mathr> factor 360
2^3 · 3^2 · 5
mathr> 5!
120
mathr> 20!
2432902008176640000
mathr> |-5|
5
mathr> 7 mod 3
1
mathr> gcd(12, 8)
4
mathr> C(5, 2)
10
mathr> \binom{5}{2}
10
mathr> mathml x^2 + 1
<math xmlns="http://www.w3.org/1998/Math/MathML"><mrow><msup><mi>x</mi><mn>1</mn></msup><mo>+</mo><mn>1</mn></mrow></math>
mathr> mathml import <mfrac><mn>1</mn><mn>2</mn></mfrac>
1/2
mathr> serialize sexpr 2*x + 1
(add (mul (num 2) (var x)) (num 1))
mathr> serialize json x^2
{"t":"pow","a":{"t":"var","v":"x"},"b":{"t":"num","v":2}}
mathr> serialize rpn import 2 x * 1 +
2*x + 1
mathr> interval x^2 + 1 with x=[-2,3]
[1, 10]
mathr> interval sin(x) with x=[0,6.283185307179586]
[-1, 1]
mathr> qr 12 -51 4 | 6 167 -68 | -4 24 -41
QR ok (max reconstruction error = 0.00e+00)
Q =
...
R =
...
mathr> ad sin(x^2) at x=1.5
f(x) = 0.997495, f'(x) = -0.313312
mathr> ad grad x^2 + y^3 with x=2,y=3
∇f = [∂f/∂x = 4, ∂f/∂y = 27]
mathr> big modpow 2 100 1000000007
2^100 ≡ 97637128 (mod 1000000007)
mathr> quit
Web Notebook
Launch a Jupyter-like web notebook with KaTeX math rendering:
Example Notebooks
| File | Topics |
|---|---|
examples/notebooks/demo.mnb |
General overview |
examples/notebooks/calculus.mnb |
Differentiation, integration, Taylor series, gradients |
examples/notebooks/fractions.mnb |
Exact fraction arithmetic with \frac and rat |
examples/notebooks/solving.mnb |
Root finding, polynomial roots, simplification |
examples/notebooks/linear_algebra.mnb |
LU, Cholesky, SVD, eigenvalues, FFT, stats |
examples/notebooks/number_theory.mnb |
GCD, primality, factorization, Diophantine, discrete log |
examples/notebooks/special_functions.mnb |
Gamma, erf, Bessel, sinc |
examples/notebooks/latex_demo.mnb |
LaTeX/TeX input with \sin, \frac, \Gamma |
examples/notebooks/series_interp.mnb |
Taylor/Laurent series, splines, Chebyshev, Legendre |
examples/notebooks/notebook_features.mnb |
Shared context, text cells, inline plots, Markdown, execution counters |
Notebook Features
- Shared context across cells — variables and functions defined in one cell (via
let/fn) are available in subsequent cells, just like Jupyter - Cell types — Math cells (evaluated with KaTeX rendering) and Text cells (Markdown-rendered documentation)
- Inline plots —
plotcommands render PNG images directly in the notebook (no file management) - Cell management — add, delete, duplicate, move up/down, and toggle cell type
- Execution status — each cell shows running/done/error status with
In [n]:execution counters - Context panel — collapsible panel showing all bound variables and user functions
- Reset & Run All — resets the shared context and re-evaluates all cells in order
- Markdown rendering — text cells render Markdown (headings, lists, code, blockquotes) via marked.js
- KaTeX math rendering — input expressions and output results rendered as math notation
- Step-by-step solving — shows intermediate steps for
diff,solve,taylor,integrate,simplify,rat,laurent - Exact fraction arithmetic —
\frac{1}{2} + \frac{3}{4}evaluates to5/4, not1.25 - Live input preview — each cell shows a rendered math/Markdown preview as you type
- Save / load —
.mnbJSON file format with cells of TeX/math input and evaluated output - Keyboard shortcuts — Shift/Cmd/Ctrl+Enter to run a cell, Alt+Enter to run and add a new cell
.mnb File Format
REST API
| Method | Path | Description |
|---|---|---|
GET |
/ |
Serve web UI HTML |
POST |
/api/eval |
Evaluate expression (updates shared context); returns {input, output, steps} |
GET |
/api/notebook |
Get current notebook as JSON |
POST |
/api/notebook |
Replace notebook state (auto-saves to file) |
POST |
/api/save |
Save notebook to file |
POST |
/api/reset |
Reset the shared evaluation context |
GET |
/api/context |
Get current variables and user functions |
Crate API
use *;
// Evaluate an expression
let val = eval_str?;
// Symbolic differentiation and integration
let expr = parse?;
let deriv = differentiate?;
let integr = integrate?; // x³/3
// FFT magnitude spectrum
let samples = vec!;
let mags = magnitude_spectrum?;
// Matrix operations
let m = from_rows?;
let det = m.determinant?;
let inv = m.inverse?;
let lu = m.lu?;
let chol = m.cholesky?;
let svd = m.svd?; // A = U Σ Vᵀ
let eigen = m.power_iteration?;
// Descriptive statistics
let data = vec!;
let s = summary?;
// Number theory
let primes = sieve_primes;
let fib50 = fibonacci;
let is_prime = is_prime_miller_rabin;
let cf = continued_fraction?; // [3; 7]
let j = jacobi_symbol; // -1
let = diophantine?; // (14, -7)
let dl = discrete_log; // Some(7)
// ODE: solve y' = y, y(0) = 1, on [0, 1]
let y = rk4?;
// Taylor series expansion
let series = taylor_series_str?;
// Interpolation
let pts = vec!;
let y = lagrange_interp?;
let sp = new?;
let v = sp.eval;
// Chebyshev series
let coeffs = chebyshev_coefficients;
let y_eval = chebyshev_eval;
// Gauss–Legendre quadrature
let = gauss_legendre;
// Special functions
let g = gamma;
let j0 = bessel_j0;
let j5 = bessel_jn;
// Numerical integration
let integral = integrate_romberg?;
// Newton's method for nonlinear systems
let system = ;
let sol = newton_system?;
Modules
| Module | Description |
|---|---|
expr |
Expression AST (Expr) with canonicalization and equality |
parser |
Recursive-descent parser with LaTeX/TeX support |
eval |
Tree-walking evaluator with Context (variables, functions) |
simplify |
Constant folding and algebraic identity simplification |
symbolic |
Symbolic differentiation and integration |
calculus |
Numerical derivatives, quadrature, gradients, Romberg, Monte Carlo, Fourier series |
solver |
Bisection, Newton, secant, polynomial roots, Newton for systems, VAS root isolation |
fft |
Cooley–Tukey FFT, convolution, cross-correlation, windows |
complex |
Generic complex number type |
matrix |
Matrix arithmetic, determinant, inverse, solve, LU, QR, Cholesky, SVD, eigenvalues, rank |
stats |
Descriptive statistics, correlation, regression, stochastic primitives |
numtheory |
GCD, LCM, primality, factorization, sieve, CRT, totient, Jacobi, Diophantine, continued fractions, discrete log |
bigint |
Arbitrary-precision integers: primality (Miller–Rabin), factorization (Pollard's rho), GCD, LCM, factorial, Fibonacci, binomial, mod_pow, totient |
autodiff |
Automatic differentiation via dual numbers: derivative, gradient, jacobian, Dual type with full arithmetic |
serialize |
Expression serialization: S-expressions, JSON, RPN (to_sexpr/from_sexpr, to_json/from_json, to_rpn/from_rpn) — all round-trip via Expr::equals |
interval |
Interval arithmetic for rigorous bounds: Interval type with arithmetic, elementary functions, eval_interval over Expr AST |
bigdec |
Arbitrary-precision decimal arithmetic: pi/e/sqrt/exp/ln/trig to N significant digits, eval_decimal over Expr AST, dec REPL command |
limit |
Symbolic limits: direct substitution, recursive L'Hôpital's rule, numeric probing fallback, limits at ±∞, pole/DNE detection |
poly |
Polynomial expansion/collection over Expr: multivariate expand, to_poly/poly_to_expr conversions |
apart |
Partial fraction decomposition of rational functions (apart <expr> [var]): long division, numeric factorization, coefficient solve |
ode |
Euler, RK4, RK4 systems, adaptive RKF45 |
taylor |
Symbolic Taylor series expansion |
laurent |
Laurent series expansion around poles |
interpolate |
Lagrange, Newton, linear, cubic spline, Chebyshev, Legendre, Gauss–Legendre |
special |
Gamma, Beta, erf, erfc, sinc, incomplete gamma, Bessel J_0/J_1/J_n, digamma/trigamma/polygamma, harmonic, zeta/Hurwitz, elliptic integrals K/E/F/E_inc |
fastmath |
Chebyshev-based fast approximations of sin, cos, tan, exp, log, sqrt, pow |
rational |
Exact rational arithmetic (Rational type), eval_rational for exact AST evaluation |
notebook |
.mnb notebook format, JSON cells with TeX/math input + output, cell types (math/text), cell reordering, shared context |
server |
Minimal HTTP server for web notebook UI (KaTeX rendering, step-by-step solving) |
plot |
PNG plotting via plotters |
Dependencies
| Crate | Purpose |
|---|---|
clap |
CLI argument parsing |
anyhow |
Error handling in binary |
thiserror |
Error types in library |
rustyline |
REPL line editing with history |
plotters |
PNG plot rendering |
num-traits |
Numeric trait bounds |
num-bigint |
Arbitrary-precision integers |
num-integer |
Integer trait methods (mod_floor, is_even) |
bigdecimal |
Arbitrary-precision decimal backend for bigdec |
approx (dev) |
Float comparison in tests |
License
Apache-2.0