radlang — Math (math)
This document covers the math namespace: elementary functions, rounding,
comparison helpers, and (pseudo-)random numbers.
For language fundamentals see the Overview.
Overview
math is a compiler-intrinsic namespace. The name is reserved and
dispatched directly to the C math library — it needs no import:
fn main() {
float d = math.sqrt(2.0) // 1.4142135623730951 (sys.output(d) prints 1.41421)
float h = math.max(3.0, 9.0) // 9.0
sys.output(d)
}sys.output shows a float to 6 significant digits (2.71828, 12); use
value.toShortest() or value.toFixed(n) (number formatting)
for more. Numeric arguments are accepted as int or float — integers are widened to
floating point automatically. Elementary functions return float (64-bit),
except the integer form of random and void seed. Typed buffer/matrix helpers
have their own list/byte return types.
math.matmul(left, right, rows, shared, columns): float[] multiplies checked
row-major f64 lists and returns fresh storage. See MLIR kernels for
shape checks and optional run/build --mlir specialization. Lossless native
math.f64From/math.f64To binary copies are documented with native calls.
Powers and roots
math.sqrt(x) : float // square root
math.pow(base, e) : float // base raised to efn main() {
sys.output(math.sqrt(144.0)) // 12
sys.output(math.pow(2.0, 10.0)) // 1024
sys.output(math.pow(9, 0.5)) // 3 (ints are widened)
} Rounding
math.floor(x) : float // round toward -infinity
math.ceil(x) : float // round toward +infinity
math.round(x) : float // round to nearest
math.abs(x) : float // absolute valuefn main() {
sys.output(math.floor(3.7)) // 3
sys.output(math.ceil(3.2)) // 4
sys.output(math.round(3.5)) // 4
sys.output(math.abs(-8.0)) // 8
} Exponential
math.exp(x) : float // e raised to xfn main() {
sys.output(math.exp(1.0)) // 2.71828
sys.output(math.exp(0)) // 1 (ints are widened)
}math.exp overflows to infinity above about 709.78 (math.exp(710.0)),
reaches the smallest subnormal at math.exp(-745.0), and returns NaN for NaN.
Logarithms
math.log(x) : float // natural log (base e)
math.log2(x) : float // base 2
math.log10(x) : float // base 10fn main() {
sys.output(math.log10(1000.0)) // 3
sys.output(math.log2(8.0)) // 3
} Trigonometry
math.sin(x) : float
math.cos(x) : float
math.tan(x) : float
math.tanh(x) : float // hyperbolic tangent, in (-1, 1)Angles are in radians. math.tanh is 1.0 from about x = 19.1 up (and
-1.0 below the negative of that), and NaN for NaN.
fn main() {
sys.output(math.sin(0.0)) // 0
sys.output(math.cos(0.0)) // 1
} Comparison and clamping
math.min(a, b) : float // smaller of two
math.max(a, b) : float // larger of two
math.clamp(x, lo, hi) : float // constrain x to [lo, hi]fn main() {
sys.output(math.min(3.0, 9.0)) // 3
sys.output(math.max(3.0, 9.0)) // 9
sys.output(math.clamp(15.0, 0.0, 10.0)) // 10
sys.output(math.clamp(-5.0, 0.0, 10.0)) // 0
} Naming the result type: <int>, <long>, <float>
The whole-number-capable functions take an explicit result type (1.40.32):
math.floor<T>(x) / ceil<T>(x) / round<T>(x) : T // round, then convert to T
math.abs<T>(x) : T
math.min<T>(a, b) / max<T>(a, b) : T
math.clamp<T>(x, lo, hi) : T
math.pow<T>(base, exp) : TT is int, long or float. With int or long:
floor,ceilandroundtake any number and convert the rounded result astoInt()/toLong()do: out of range saturates to the type’s minimum or maximum, and NaN gives 0.abs,min,max,clampandpowcompute in that integer type, with no float in between, solongvalues past 2^53 stay exact. An argument wider thanT(a float for<int>, a long for<int>) is a compile error; convert it first or name a widerT.math.abs<int>of the minimum int saturates to the maximum;math.pow<int>wraps on overflow like repeated*, and a negative exponent raises an error.
fn main() {
int n = math.floor<int>(2.7) // 2
int m = math.max<int>(3, 9) // 9
var big = math.round<long>(5e9 + 0.4) // 5000000000 (long)
sys.output(math.pow<int>(2, 10)) // 1024
}Without <T> the calls are unchanged and return float.
Radix sorting
math.sort.radix(values) returns a sorted copy of an int[] using an
adaptive stable radix sort. It handles signed integers and chooses radix width
and pass count from the observed value range; the input list is unchanged.
int[] values = [3, -1, 2, -100, 0, 3]
int[] sorted = math.sort.radix(values)Additional native numeric sort strategies are available:
math.sort.count(values) // dense ranges; falls back for sparse ranges
math.sort.timsort(values) // stable; exploits existing ordered runs
math.sort.intro(values) // quicksort-style; heapsort worst-case fallback
math.sort.pdq(values) // pattern-defeating quicksort
math.sort.radix(values, 4) // parallel radix with four workersEach returns a sorted copy and accepts numeric lists. The default .sort() now
adaptively selects dense counting sort, radix sort, or a typed comparison
kernel. long[], unsigned integer types, and floating-point lists use direct
native typed kernels as well. The optional radix thread count uses the
persistent runtime worker pool for sufficiently large numeric lists.
Random numbers
math.random() : float // in [0.0, 1.0)
math.random(min, max) : int // integer in [min, max] (inclusive)
math.seed(n: int) : void // seed the generatormath.random()with no arguments returns afloatin the half-open range[0.0, 1.0).math.random(min, max)returns anintuniformly in the inclusive range[min, max]— ideal for dice, indices, and picks.math.seed(n)seeds the underlying generator so a run is reproducible. Seed with the same value to get the same sequence.
fn main() {
float r = math.random() // e.g. 0.37454
int dice = math.random(1, 6) // 1..6 inclusive
sys.output(dice)
math.seed(42)
sys.output(math.random(1, 100)) // deterministic given the seed
}Note. This is a standard pseudo-random generator (C
rand) — fine for games, sampling, and simulations, but not cryptographically secure. For tokens, salts, and nonces usecrypto.randomBytes(seecrypto.md).
Packed float32 buffers
Packed activations use byte[] storage with four bytes per IEEE-754 float32.
Radlang float remains float64; conversions round to float32 on writes. The
bytes use native byte order (little-endian on supported Apple Silicon/x86
platforms) and can be passed to native quantized dot kernels or GPU uploads.
byte[] activation = math.f32Alloc(2048) // zero-filled; 8192 bytes
math.f32Set(activation, 0, 1.25)
float first = math.f32Get(activation, 0)
byte[] packed = math.f32From([1.0, 2.0, 3.0])
float[] unpacked = math.f32To(packed)| Function | Result | Meaning |
|---|---|---|
math.f32Alloc(count) |
byte[] |
Allocate count zeroed float32 values |
math.f32Get(buffer, index) |
float |
Read a float32 value as float64 |
math.f32Set(buffer, index, value) |
void |
Round and store one float32 value |
math.f32From(values) |
byte[] |
Copy a float[] into packed float32 storage |
math.f32To(buffer) |
float[] |
Copy packed float32 values into a float[] |
Counts and indices accept int or long and count float32 elements.
The returned byte list’s length64() counts bytes; divide by four for
the element count. Invalid sizes, partial four-byte buffers, and out-of-range
indices throw catchable errors. Buffers are ordinary mutable byte lists;
changing their raw bytes changes the stored floating-point representation.
Quantized dot products
math.dotQ8_0(weights, offset, activations, count), math.dotQ4_K(...),
math.dotQ5_K(...), and math.dotQ6_K(...) compute a GGUF weight row’s dot
product without copying or allocating a dequantized row. Weights are byte[],
including mapped files; offset is an int or long byte offset. Activations
are either float[] or packed native float32 byte[] from math.f32From.
count is an int element count: a multiple of 32 for Q8_0, or 256 for the
K formats. The encoded block sizes are 34, 144, 176, and 210 bytes respectively.
Invalid bounds or partial blocks throw a catchable error.
The result is a float, computed with float32 accumulation. Apple Silicon
uses NEON; other targets use a scalar fallback. Float64 activations are rounded
to float32 during the dot product. Floating-point reduction order can produce
small differences between scalar and SIMD results. Calls allocate no heap memory
and can run concurrently from threaded list operations.
// activation: float[] of 2048 values; modelBytes: the mapped GGUF file
float score = math.dotQ4_K(modelBytes, rowOffset, math.f32From(activation), 2048) Reusable integer activation blocks
math.quantizeQ8K(activations) accepts float[] or packed float32 byte[]
and returns a byte[] with one 292-byte block per 256 activations. Input
length must be a multiple of 256 and all values must be finite float32 values.
Each block stores a float32 scale, 256 signed quantized bytes, and 16 signed
partial sums. Treat the result as opaque and reuse it across all rows of a
matrix; changing the original activations requires quantizing again.
byte[] qx = math.quantizeQ8K(activation)
float result = math.dotQ4_KQ8K(weights, rowOffset, qx, 2048)dotQ4_KQ8K, dotQ5_KQ8K, and dotQ6_KQ8K have the same offset and
element-count conventions as their float-activation counterparts. They unpack
weight nibbles into integer SIMD registers and compute integer dot products,
with NEON dot-product instructions where available and portable fallbacks.
Quantizing adds rounding error: the scale is max(abs(block)) / 127 and
values round to the nearest signed integer. These APIs are opt-in; existing
dotQ4_K/Q5_K/Q6_K calls retain float32 activations. Validate model accuracy
before adopting activation quantization.
Quick reference
| Call | Returns | Purpose |
|---|---|---|
math.sqrt(x) |
float | Square root |
math.pow(b, e) |
float | Exponentiation |
math.abs(x) |
float | Absolute value |
math.floor(x) / ceil(x) / round(x) |
float | Rounding |
math.log(x) / log2(x) / log10(x) |
float | Logarithms |
math.sin(x) / cos(x) / tan(x) |
float | Trigonometry (radians) |
math.min(a, b) / max(a, b) |
float | Smaller / larger |
math.clamp(x, lo, hi) |
float | Constrain to a range |
math.floor<T>(x) and the other <T> forms |
T (int, long, float) |
Named result type |
math.random() |
float | Random in [0, 1) |
math.random(min, max) |
int | Random integer in [min, max] |
math.seed(n) |
void | Seed the generator |