Tensors, element-wise math, reductions, linear algebra, random numbers, signal processing, sparse arrays, and numeric loading.
The math module is built in — no file needed. It provides tensor creation, element-wise operations, reductions, shape operations, and linear algebra. After use math, all functions are called directly (e.g. zeros[3], not math.zeros[3]).
| Function | Description | Example |
|---|---|---|
zeros[d1, d2, ...] | Tensor of zeros with given shape | Automatic differentiation · Math: tensors |
ones[d1, d2, ...] | Tensor of ones with given shape | Math: tensors |
full[d1, d2, ..., value] | Tensor filled with value (last arg) | Math: tensors |
eye[n] | n×n identity matrix | Math: reductions and linear algebra · Math: tensors |
onehot[targets, classes] | A row per target, 1 in its class's column and 0 elsewhere: the targets a vector of whole numbers from 0 to classes − 1, and the classes 1 or more (a target that is no class stops the program: onehot: 7 is not a class of 3 (0 to 2)) | Math: tensors |
diag[tensor] | Extract diagonal from a 2D tensor | Math: tensors |
linspace[start, end, n] | n evenly spaced values from start to end | Math: random, signal, special, and sparse · Math: tensors |
arange[start, end, step] | Values from start to end by step | Math: tensors · The standard library's layer: use sys |
randn[d1, d2, ...] | Normal random values (mean=0, std=1); written in Crow (see Random Numbers) | Math: tensors |
tensor[array] | Convert an array to a tensor | Frames: use frame · Automatic differentiation · Math: tensors |
| Function | Description | Example |
|---|---|---|
exp[t] | Element-wise exponential | Automatic differentiation · Math: tensors |
ln[t] | Element-wise natural log | Math: tensors |
log2[t] | Element-wise base-2 logarithm | Math: tensors |
log10[t] | Element-wise base-10 logarithm | Math: tensors |
log1p[t] | Element-wise ln(1 + x), whole: a small x keeps its digits, where ln[1.0 + x] has lost them in 1.0 + x | Math: tensors |
expm1[t] | Element-wise exp(x) − 1, whole: a small x keeps its digits | Math: tensors |
sqrt[t] | Element-wise square root | Math: tensors · Numbers and conversion · Data Types |
abs[t] | Element-wise absolute value | Frames: use frame · Math: tensors · Numbers and conversion |
sign[t] | Element-wise sign (-1, 0, or 1) | Math: tensors · Web: responses and submodules |
floor[t] | Element-wise floor | Math: tensors · Numbers and conversion · Drawing in a Browser |
ceil[t] | Element-wise ceiling | Numbers and conversion |
round[t] | Element-wise round to nearest | Math: reductions and linear algebra · Math: random, signal, special, and sparse · Math: tensors · Numbers and conversion · Data Types |
clip[t, lo, hi] | Clamp values to [lo, hi] | Math: tensors |
mod[t, divisor] | Element-wise modulo | Math: tensors |
sin[t] | Element-wise sine | Automatic differentiation · Math: tensors |
cos[t] | Element-wise cosine | Math: tensors |
tan[t] | Element-wise tangent | Math: tensors |
asin[t] | Element-wise arcsine | Math: tensors |
acos[t] | Element-wise arccosine | Math: tensors |
atan[t] | Element-wise arctangent | Math: tensors |
atan2[y, x] | Two-argument arctangent: of two numbers a number, of tensors element by element | Math: tensors |
sinh[t] | Element-wise hyperbolic sine | Math: tensors |
cosh[t] | Element-wise hyperbolic cosine | Math: tensors |
tanh[t] | Element-wise hyperbolic tangent | Math: tensors |
| Function | Returns | Example |
|---|---|---|
sum[t] | Sum of all elements (float), added as numpy adds them — pairwise, so the error grows as log n and sum[x] is numpy.sum(x) to the last digit; of a list of ints, an int with every digit (sum[xs] % 10 of digits pushed one by one; Vijay, 2026-10-29) — a list written down is a vector, and a list whose ints can fail (int[c] of text) is read as numbers, so either sums to a float | Frames: use frame · Automatic differentiation · Math: reductions and linear algebra · Math: random, signal, special, and sparse · Math: tensors · Importing with use · Aliased Imports · Project: Analyzing Data · The Database Layer · Views and Live Updates |
mean[t] | Mean of all elements (float): the sum over the count | Automatic differentiation · Math: reductions and linear algebra · Math: tensors · Importing with use |
min[t] | Minimum element (float): NaN where the tensor holds one, as numpy's and IEEE 754's minimum answer and as sum carries one; of no numbers the program stops (min of nothing: an empty tensor has no smallest number), as numpy and Python raise — min[t, axis] of an empty axis too. (Until 2026-10-18 a NaN had been passed over and an empty tensor answered inf.) | Math: reductions and linear algebra · Numbers and conversion |
max[t] | Maximum element (float): NaN where the tensor holds one; of no numbers the program stops (max of nothing: an empty tensor has no largest number) | Frames: use frame · Math: reductions and linear algebra · Numbers and conversion · Testing |
prod[t] | Product of all elements (float) | Math: reductions and linear algebra |
argmax[t] | Index of maximum element (int) | Math: reductions and linear algebra · Math: tensors |
argmin[t] | Index of minimum element (int) | Math: reductions and linear algebra |
All reductions except argmax/argmin accept an optional axis parameter: sum[t, axis] reduces along that axis and returns a tensor instead of a scalar.
| Function | Returns | Example |
|---|---|---|
argsort[t] | The indices that would sort the numbers, ascending: a list of ints, as range answers one, so xs[order[0]] reads the smallest (it had answered a tensor, whose items read as floats and indexed nothing) | Math: reductions and linear algebra |
topk[t, k] | Top k largest values, sorted descending (NumArray) | Math: reductions and linear algebra |
unique[t] | Unique values, sorted (NumArray) | Frames: use frame · Math: reductions and linear algebra |
where[cond, a, b] | Element-wise: a where cond≠0, else b (NumArray); cond a mask too — where[v gt 15.0, v, 0.0 * v] — as a mask is numbers where numbers are asked (true 1, false 0; sum[v gt 15.0] counts); a mask has its tensor's rank, so where of a vector's is a vector (parity 500) | Frames: use frame · Automatic differentiation · Math: reductions and linear algebra · Math: tensors · Project: Analyzing Data |
Note: sort[t] is a core builtin (not in the math module) that works on both arrays and tensors.
| Function | Returns | Example |
|---|---|---|
cumsum[t] | Cumulative sum (NumArray, same shape) | Math: reductions and linear algebra |
cumprod[t] | Cumulative product (NumArray, same shape) | Math: reductions and linear algebra |
| Function | Returns | Example |
|---|---|---|
stack[tensors] | Stack tensors along new axis 0 (NumArray) | Frames: use frame · Math: tensors · Views: the whole element vocabulary · View Blocks · Reactive State and Events · Slow Work and the Live Loop · Testing a Live App · Charts and Styling · The Element Vocabulary · Derivations |
stack[tensors, axis] | Stack tensors along new axis (NumArray) | Frames: use frame · Math: tensors · Views: the whole element vocabulary · View Blocks · Reactive State and Events · Slow Work and the Live Loop · Testing a Live App · Charts and Styling · The Element Vocabulary · Derivations |
Note: concat[a, b, axis] is a core builtin (not in the math module) — one merge operation for all arrays and tensors. It replaced the former batch.
Note: slice[t, start, end] is a core builtin (not in the math module) that works on arrays, tensors, and strings.
Element-wise operations on tensors with different shapes automatically broadcast following NumPy rules:
use math
a = reshape[linspace[1, 3, 3], 3, 1] --- shape [3, 1]
b = reshape[linspace[10, 40, 4], 1, 4] --- shape [1, 4]
c = a + b --- shape [3, 4]
Broadcasting works with all element-wise operators: +, -, .*, ./, .^.
Incompatible shapes (e.g. [3] + [4]) are refused before the program runs where both shapes are known (see Tensor Arithmetic), and stop the program where it runs where they are not, with the same words in both modes.
Tensors can be indexed with another tensor to gather elements by index:
a = linspace[10, 50, 5]
indices = linspace[0, 2, 3]
y = a[indices] --- gathers elements at indices 0, 1, 2
Negative indices are supported (wrap around from the end). The result tensor has the same shape as the index tensor. A tensor is read at the positions of any rank's flattened numbers (m[[0, 3]] of [[1.0, 2.0], [3.0, 4.0]] is [1, 4]), and a list of whole numbers gathers as the tensor of them does — t[range[a, b]], a list grown by push (the read had been typed as one number's: interpreted it stopped, and compiled it did not build). Inside a function grad differentiates the gather is differentiated (see Automatic Differentiation).
| Function | Description | Example |
|---|---|---|
reshape[t, d1, d2, ...] | Reshape to new dimensions | Automatic differentiation · Math: tensors |
flatten[t] | Flatten to 1D | Automatic differentiation · Math: tensors |
transpose[t] | Transpose (swap last two axes) | Math: reductions and linear algebra · Math: tensors |
| Function | Description | Example |
|---|---|---|
a * b | Matrix multiplication (use * operator), over the last two axes; the axes before them are a batch | Views: the whole element vocabulary · Reactive State and Events · Testing a Live App · The Element Vocabulary |
solve[a, b] | Solve linear system Ax = b | Math: reductions and linear algebra · Math: tensors |
inv[a] | Matrix inverse | Math: reductions and linear algebra |
det[a] | Determinant (returns float) | Math: reductions and linear algebra · Math: tensors |
svd[a] | SVD → returns [U, S, Vt] | Math: reductions and linear algebra |
qr[a] | QR decomposition → returns [Q, R], the reduced one (numpy's and PyTorch's): Q's columns orthonormal, m × min(m, n), R upper triangular, min(m, n) × n, and Q · R is a | Math: reductions and linear algebra |
cholesky[a] | Cholesky (L*L^T) for symmetric positive-definite | Math: reductions and linear algebra |
eigen[a] | Eigenvalues → returns [real, imag] | Math: reductions and linear algebra |
norm[x] | L2 (Euclidean) norm (returns float) | Math: reductions and linear algebra |
norm[x, p] | Lp norm (p=1 for L1, inf for L∞) | Math: reductions and linear algebra |
dot[a, b] | Vector dot product (inner product, returns float) | Frames: use frame · Math: reductions and linear algebra |
pinv[a] | Moore-Penrose pseudo-inverse | Math: reductions and linear algebra |
lstsq[a, b] | Least-squares solve: minimize ‖Ax − b‖² | Math: reductions and linear algebra |
triu[a] | Upper triangular part of matrix | Math: reductions and linear algebra |
tril[a] | Lower triangular part of matrix | Math: reductions and linear algebra |
rank[a] | Matrix rank (count of singular values above tolerance) | Math: reductions and linear algebra |
cond[a] | Condition number (largest singular value / smallest) | Math: reductions and linear algebra |
| Function | Description | Example |
|---|---|---|
seed[n] | Set the program's RNG seed: every later draw, tensors and the core rand[] alike, is repeatable and identical in both modes. Statements run in the order written, and a loop that draws runs in order (§14), so a seeded program draws the same numbers on every run. A page's (a program that holds state) declarations are set before its other top-level lines run, so its top-level seed[n] runs before them, wherever it is written: the facts' draws are seeded too (Vijay, 2026-10-29: they had been drawn unseeded) | Automatic differentiation · Math: random, signal, special, and sparse · Math: tensors |
randn[d1, d2, ...] | Standard normal (mean=0, std=1): Box–Muller over two uniform draws a value, written in Crow (src/modules/math.co, design rule 20); a negative size stops the program | Math: tensors |
normal[mean, std, d1, d2, ...] | Normal with custom mean/std: mean + std · randn, written in Crow; a negative std stops the program | Math: random, signal, special, and sparse |
uniform[low, high, d1, d2, ...] | Uniform in [low, high): uniform[0.0, 1.0, 2, 3] is a 2×3 tensor of values in [0, 1) | Math: random, signal, special, and sparse |
poisson[lambda, d1, d2, ...] | Poisson distribution | Math: random, signal, special, and sparse |
bernoulli[p, d1, d2, ...] | Bernoulli (0.0 or 1.0) | Automatic differentiation · Math: random, signal, special, and sparse |
gamma_dist[alpha, beta, d1, ...] | Gamma distribution of shape α and rate β — the mean α/β, as the (α, β) of the textbooks, R, Stan and PyTorch: gamma_dist[1.0, λ, n] is exponential[λ, n]'s distribution (until 2026-10-18 β was a scale, the mean α·β) | Math: random, signal, special, and sparse |
beta_dist[alpha, beta, d1, ...] | Beta distribution | Math: random, signal, special, and sparse |
exponential[lambda, d1, ...] | Exponential distribution | Math: random, signal, special, and sparse |
shuffle[x] | Random permutation of tensor elements | Math: random, signal, special, and sparse |
choice[x, n] | Random sample of n elements (no replacement) | Math: random, signal, special, and sparse |
permutation[n] | Random permutation of 0..n | Math: random, signal, special, and sparse |
rand is core's: rand[] is one float in [0, 1), and rand[n] and rand[min, max] are ints (see Core Builtins). A tensor of values in [0, 1) is uniform[0.0, 1.0, d1, …].
Design Note: no tensor rand. Considered: rand[d1, d2, …] for a tensor of uniform values in [0, 1), as NumPy spells it. The math module had it until March 2026, when its functions became callable without math. and core's rand kept the name; this table went on listing it, and its examples made ints (rand[2, 3] is 2 or 3). Rejected: rand[5] and rand[2, 3] are core's, an int below 5 and an int from 2 to 3, so the same call would mean two things, and use math would change what a program computes. Decided: uniform[0.0, 1.0, …] makes the tensor, the one way to.
| Function | Description | Example |
|---|---|---|
fft[x] | 1D FFT → returns [real, imag] tensors | Math: random, signal, special, and sparse |
ifft[real, imag] | Inverse 1D FFT → returns real tensor | Math: random, signal, special, and sparse |
fft2[m] | 2D FFT → returns [real, imag] tensors | Math: random, signal, special, and sparse |
conv[a, b] | 1D convolution (full), length = len(a)+len(b)-1; an empty signal or kernel stops the program, as numpy's refuses it (conv[[], []] had overflowed counting its answer) | Math: random, signal, special, and sparse |
conv2d[a, b] | 2D convolution (full); an empty signal or kernel stops the program, as conv's does | Math: random, signal, special, and sparse |
hamming[n] | Hamming window of length n | Math: random, signal, special, and sparse |
hanning[n] | Hanning (Hann) window of length n | Math: random, signal, special, and sparse |
stft[x, window_size, hop_size] | Short-Time Fourier Transform → [real, imag] 2D tensors [frames × window_size] | Math: random, signal, special, and sparse |
spectrogram[x, window_size, hop_size] | Power spectrogram (magnitude² of STFT) → 2D tensor | Math: random, signal, special, and sparse |
lowpass[x, cutoff_hz, sample_rate] | FFT-based lowpass filter | Math: random, signal, special, and sparse |
highpass[x, cutoff_hz, sample_rate] | FFT-based highpass filter | Math: random, signal, special, and sparse |
bandpass[x, low_hz, high_hz, sample_rate] | FFT-based bandpass filter | Math: random, signal, special, and sparse |
| Function | Description | Example |
|---|---|---|
gamma[x] | Gamma function Γ(x), element-wise | Math: random, signal, special, and sparse |
erf[x] | Error function erf(x), of a number or element-wise over a tensor (it had taken a tensor only) | Math: random, signal, special, and sparse |
fma[a, b, c] | a × b + c rounded once: the fused multiply-add a compiled loop accumulates with (pandas's rolling kernels, scikit-learn's row norms, scipy's sparse products), so a sum held to one of them runs with it — total = fma[x, x, total] | Math: random, signal, special, and sparse |
bessel[x, n] | Bessel function J_n(x), element-wise | Math: random, signal, special, and sparse |
factorial[x] | Factorial x! = Γ(x+1), element-wise — a whole number's exactly up to 22! (each a float), and Γ as libm computes it | Math: random, signal, special, and sparse |
choose[n, k] | Binomial coefficient C(n,k), element-wise | Math: random, signal, special, and sparse · The Element Vocabulary |
Complex values are represented as [real_tensor, imag_tensor] pairs.
| Function | Description | Example |
|---|---|---|
complex[re, im] | Create complex value → [real, imag] | Math: random, signal, special, and sparse |
real[c] | Extract real part tensor | Math: random, signal, special, and sparse |
imag[c] | Extract imaginary part tensor | Math: random, signal, special, and sparse |
magnitude[c] | Magnitude |c| = sqrt(re² + im²) | Math: random, signal, special, and sparse |
phase[c] | Phase angle = atan2(im, re) | Math: random, signal, special, and sparse |
conjugate[c] | Complex conjugate → [re, -im] | Math: random, signal, special, and sparse |
Sparse matrices store only non-zero entries, using CSR (Compressed Sparse Row) format internally. They use the same operators as dense arrays — the runtime dispatches to sparse-optimized algorithms automatically.
| Function | Description | Example |
|---|---|---|
sparse[dense_array] | Convert dense 2D array to sparse | Math: random, signal, special, and sparse |
sparse[rows, cols, vals, shape] | Create sparse from COO triplets (row indices, column indices, values, [nrows, ncols]) | Math: random, signal, special, and sparse |
dense[s] | Convert sparse matrix back to dense array | Math: random, signal, special, and sparse |
nnz[s] | Number of stored non-zero entries | Math: random, signal, special, and sparse |
spmv[s, v] | Sparse matrix × dense vector (the same product as s * v) | Math: random, signal, special, and sparse |
s * v | Sparse × dense matmul (vector or matrix) | Strings and Interpolation |
s + s2 | Sparse + sparse addition | Strings and Interpolation |
solve[s, b] | Solve sparse linear system s·x = b | Math: reductions and linear algebra · Math: tensors |
use math
--- dense to sparse
s = sparse[eye[3]]
log[s] --- sparse[3x3, nnz=3]
--- COO creation
s2 = sparse[[0, 1, 2], [0, 1, 2], [5, 6, 7], [3, 3]]
--- sparse matmul
r = s * [1, 2, 3]
--- sparse add
s3 = s + s2
--- back to dense
d = dense[s3]
--- sparse solve
x = solve[s2, [10, 12, 14]]
| Function | Description | Example |
|---|---|---|
load[path] | Load a table of numbers directly into a 2D tensor: a CSV file, or JSON records or Parquet, from a file, a URL or an S3 object (error-value on failure) | Databases: use db · Frames: use frame · Web: responses and submodules · Project: Analyzing Data · Reactive State and Events |
load[path] reads a CSV file with a header row and parses all values as floats into a 2D tensor (rows × columns). This is much faster than csv[path] (io module) for numeric data because it avoids creating intermediate string maps.
use math
data = load['data.csv']
log[data.shape] --- [1000, 10]
log[sum[data]] --- total of all values
The statistics (a median, a variance, a test, a fit), the activations, losses and layers of a network, the classical models and the optimisers are written in Crow over these builtins, in the pie repository (github.com/agncrow/pie): each a package a program installs as any dependency and calls qualified — nn.relu[x], stats.median[x] — held to the library it follows (PyTorch, scipy, scikit-learn). The math module keeps what a formula stands on: the tensors, their kernels and grad.
Design Note: the statistics and the networks are a package's. Considered: keeping them as standard modules (math.stats, math.nn) beside the kernels (rejected: each is a formula over the builtins, so the language carried a library's choices — which tests, which layers — and two homes grew for one domain: the modules here, the models and gpt packages there). Decided (Vijay, 2026-11-07): crow keeps what its compiler must know and what only Rust can be — the tensor and the frame, their operators and kernels, and grad, which is how x * w + b is differentiated with the language's own operators — and every algorithm written over them is pie's. Pie depends on crow; crow depends on nothing of pie's.
Design Note: a module written in Crow declares its functions by writing them. Considered (decided 2026-10-04, undone 2026-10-18): the builtin table stating every builtin's contract whether its body is Rust or Crow — a row per Crow-written function, the arguments read as the row's parameters take them (a list of numbers converted to a tensor), a misuse refused with the row's own words (lines[] takes text, got an int), a value JSON can hold handed to the function as its JSON text and read back with json[…]. Rejected now: the compiler then names every module's function (design rule 24), a module cannot be written without a row written in Rust beside it, and the row was a second signature that drifted from the function's. Decided (2026-10-18): a module's exported functions are its declaration (section 13's opening) — inlined where the program reaches them, by a bare name, the module's path, an alias, or as a value, and typed by their use, a copy per signature; a helper begins with an underscore. A misuse is refused where the formula first cannot take the kind, the refusal naming the function the program called and the program's line (in lines: … got an int); the body's own stops name that line too, never a line of the module's source. A module's function is read in the module's own scope: the program's functions, imports, aliases and elements are invisible in it — the protocol's local lines, indexed lines[0], stays its local in a program with a lines of its own, and a program names its functions as it likes (parity 162) — and a module's functions are inlined only where the program reaches them: a program that uses math without load carries none of the protocol. A function that reads a value JSON can hold (sign's claims, msgpack's value) takes the value the program holds and reads it as its JSON inside (json[encode[claims]]). The rows left (an effect's, a rest parameter's, a driver's) keep the earlier rule until their phases; the IR verifier holds each one's function to its row.
| Constant | Description | Example |
|---|---|---|
pi | π = 3.14159... | |
e | Euler's number e = 2.71828... | Frames: use frame |
inf | Positive infinity | |
nan | Not a number |
A constant read through its module (math.pi, math.e) is the number it holds, as the bare name is: math.cos[math.pi * x] takes a float (parity 507; it had been typed as nothing known, and the compiled call reached the decimal's cosine).
use math
a = zeros[3, 3]
b = eye[3]
c = a * b
d = det[b] --- 1.0
--- constants
log[pi] --- 3.141592653589793
--- properties
log[a.shape] --- [3, 3]
log[a.dtype] --- float
log[a.device] --- cpu
Generated by crow test --docs --write from the language specification, section 11 and 13. Edit the spec, not this page.