Math & Stats
Tova provides essential math functions for numerical computation, statistics, and number formatting.
Constants
PI
PI -> Float // 3.141592653589793The ratio of a circle's circumference to its diameter.
area = PI * radius ** 2
circumference = 2 * PI * radiusE
E -> Float // 2.718281828459045Euler's number, the base of natural logarithms.
INF
INF -> Float // InfinityPositive infinity. Useful as an initial value for finding minimums.
var best = INF
for val in data {
if val < best { best = val }
}Rounding
abs
abs(n) -> NumberReturns the absolute value of a number.
abs(-5) // 5
abs(5) // 5
abs(-3.14) // 3.14
abs(0) // 0floor
floor(n) -> IntRounds a number down to the nearest integer.
floor(3.7) // 3
floor(3.2) // 3
floor(-1.5) // -2
floor(5) // 5ceil
ceil(n) -> IntRounds a number up to the nearest integer.
ceil(3.2) // 4
ceil(3.7) // 4
ceil(-1.5) // -1
ceil(5) // 5round
round(n) -> IntRounds a number to the nearest integer.
round(3.5) // 4
round(3.4) // 3
round(-1.5) // -1
round(7) // 7trunc
trunc(n) -> IntTruncates a number toward zero (removes the decimal part).
trunc(3.7) // 3
trunc(-3.7) // -3
trunc(5) // 5sign
sign(n) -> IntReturns -1, 0, or 1 indicating the sign of a number.
sign(-42) // -1
sign(0) // 0
sign(100) // 1Constraining
clamp
clamp(n, lo, hi) -> NumberConstrains a number to be within the range [lo, hi].
clamp(15, 0, 10) // 10
clamp(-5, 0, 10) // 0
clamp(5, 0, 10) // 5Powers & Roots
sqrt
sqrt(n) -> FloatReturns the square root of a number.
sqrt(16) // 4
sqrt(2) // 1.4142135623730951pow
pow(base, exp) -> NumberRaises base to the power of exp. The ** operator is an equivalent alternative.
pow(2, 10) // 1024
pow(3, 3) // 27Trigonometry
sin, cos, tan
sin(n) -> Float
cos(n) -> Float
tan(n) -> FloatStandard trigonometric functions. Input is in radians.
sin(0) // 0
cos(0) // 1
sin(PI / 2) // 1
tan(PI / 4) // ~1asin, acos, atan
asin(n) -> Float
acos(n) -> Float
atan(n) -> FloatInverse trigonometric functions. Returns radians.
asin(1) // ~1.5708 (PI/2)
acos(1) // 0atan2
atan2(y, x) -> FloatReturns the angle in radians between the positive x-axis and the point (x, y).
atan2(1, 1) // ~0.7854 (PI/4)to_radians, to_degrees
to_radians(deg) -> Float
to_degrees(rad) -> FloatConvert between degrees and radians.
to_radians(180) // PI
to_degrees(PI) // 180Logarithms & Exponentials
log
log(n) -> FloatNatural logarithm (base e).
log(E) // 1
log(1) // 0log2, log10
log2(n) -> Float
log10(n) -> FloatLogarithm base 2 and base 10.
log2(8) // 3
log10(1000) // 3exp
exp(n) -> FloatReturns e raised to the power of n.
exp(0) // 1
exp(1) // ~2.718 (E)Numeric Utilities
is_nan
is_nan(n) -> BoolReturns true if the value is NaN.
is_nan(0 / 0) // true
is_nan(42) // falseis_finite
is_finite(n) -> BoolReturns true if the value is a finite number (not Infinity or NaN).
is_finite(42) // true
is_finite(INF) // false
is_finite(0 / 0) // falseis_close
is_close(a, b, tol?) -> BoolReturns true if two numbers are within tol of each other. Default tolerance is 1e-9.
is_close(0.1 + 0.2, 0.3) // true
is_close(1.0, 1.01, 0.1) // true
is_close(1.0, 2.0) // falseInteger Math
gcd
gcd(a, b) -> IntGreatest common divisor of two integers.
gcd(12, 8) // 4
gcd(7, 13) // 1lcm
lcm(a, b) -> IntLeast common multiple of two integers.
lcm(4, 6) // 12
lcm(3, 7) // 21factorial
factorial(n) -> Int | NilReturns n! (n factorial). Returns nil for negative inputs.
factorial(5) // 120
factorial(0) // 1
factorial(-1) // nilRandomness
random
random() -> FloatReturns a random floating-point number in the range [0, 1).
random() // e.g., 0.7234...random_int
random_int(lo, hi) -> IntReturns a random integer between lo and hi (inclusive).
random_int(1, 6) // e.g., 4 (dice roll)
random_int(0, 100) // e.g., 73random_float
random_float(lo, hi) -> FloatReturns a random float between lo (inclusive) and hi (exclusive).
random_float(0, 1) // e.g., 0.4823...
random_float(-1, 1) // e.g., -0.312...choice
choice(arr) -> T | NilReturns a random element from an array, or nil if empty.
choice(["red", "green", "blue"]) // e.g., "green"
choice([]) // nilsample
sample(arr, n) -> ListReturns n random elements from an array without replacement.
sample([1, 2, 3, 4, 5], 3) // e.g., [3, 1, 5]shuffle
shuffle(arr) -> ListReturns a new array with elements in random order. Does not mutate the original.
shuffle([1, 2, 3, 4, 5]) // e.g., [3, 5, 1, 4, 2]Geometry & Interpolation
hypot
hypot(a, b) -> FloatReturns the hypotenuse (length of the vector from origin to point (a, b)). More numerically stable than sqrt(a**2 + b**2).
hypot(3, 4) // 5
hypot(5, 12) // 13
hypot(0, 0) // 0lerp
lerp(a, b, t) -> FloatLinear interpolation between a and b. When t is 0, returns a; when t is 1, returns b.
lerp(0, 10, 0.5) // 5
lerp(0, 10, 0) // 0
lerp(0, 10, 1) // 10
lerp(0, 100, 0.25) // 25divmod
divmod(a, b) -> [Int, Int]Returns both the quotient and remainder as a tuple.
divmod(10, 3) // [3, 1]
divmod(7, 2) // [3, 1]
divmod(6, 3) // [2, 0]avg
avg(arr) -> FloatReturns the arithmetic mean of an array. Returns 0 for an empty array.
avg([1, 2, 3, 4, 5]) // 3
avg([10]) // 10
avg([]) // 0Async
sleep
sleep(ms) -> PromiseReturns a Promise that resolves after ms milliseconds.
await sleep(1000) // wait 1 secondStatistics
mean
mean(arr) -> Float
mean(fn) -> AggFnWhen called with an array, returns the arithmetic mean. When called with a function or string, returns an aggregation helper for use with agg().
mean([1, 2, 3, 4, 5]) // 3
mean([10]) // 10
mean([]) // 0
// As aggregation helper
table |> group_by("dept") |> agg({ avg_salary: mean("salary") })median
median(arr) -> Float | Nil
median(fn) -> AggFnWhen called with an array, returns the middle value (or average of two middle values for even-length arrays). When called with a function or string, returns an aggregation helper.
median([1, 2, 3, 4, 5]) // 3
median([1, 2, 3, 4]) // 2.5
median([]) // nilmode
mode(arr) -> T | NilReturns the most frequently occurring element. Returns nil for empty arrays.
mode([1, 2, 2, 3, 3, 3]) // 3
mode(["a", "b", "a"]) // "a"
mode([]) // nilstdev
stdev(arr) -> FloatReturns the population standard deviation.
stdev([2, 4, 4, 4, 5, 5, 7, 9]) // ~2.0
stdev([5, 5, 5]) // 0
stdev([]) // 0variance
variance(arr) -> FloatReturns the population variance.
variance([2, 4, 4, 4, 5, 5, 7, 9]) // ~4.0
variance([5, 5, 5]) // 0percentile
percentile(arr, p) -> Float | NilReturns the p-th percentile (0--100) of a numeric array. Uses linear interpolation between data points.
percentile([1, 2, 3, 4, 5], 50) // 3
percentile([1, 2, 3, 4], 25) // 1.75
percentile([10, 20, 30], 0) // 10
percentile([10, 20, 30], 100) // 30
percentile([], 50) // nilNumber Formatting
format_number
format_number(n, opts?) -> StringFormats a number with thousands separators. Options: separator (default: ","), decimals (fixed decimal places).
format_number(1234567) // "1,234,567"
format_number(1234.5, { decimals: 2 }) // "1,234.50"
format_number(1234567, { separator: "." }) // "1.234.567"to_hex
to_hex(n) -> StringConverts an integer to a hexadecimal string.
to_hex(255) // "ff"
to_hex(16) // "10"
to_hex(0) // "0"to_binary
to_binary(n) -> StringConverts an integer to a binary string.
to_binary(10) // "1010"
to_binary(255) // "11111111"
to_binary(0) // "0"to_octal
to_octal(n) -> StringConverts an integer to an octal string.
to_octal(8) // "10"
to_octal(255) // "377"to_fixed
to_fixed(n, decimals) -> FloatRounds a number to a fixed number of decimal places and returns a number (not a string).
to_fixed(3.14159, 2) // 3.14
to_fixed(3.7, 0) // 4
to_fixed(1.005, 2) // 1Arithmetic Operators
| Operator | Description | Example |
|---|---|---|
+ | Addition | 3 + 4 is 7 |
- | Subtraction | 10 - 3 is 7 |
* | Multiplication | 3 * 4 is 12 |
/ | Division | 10 / 3 is 3.333... |
% | Modulo (remainder) | 10 % 3 is 1 |
** | Exponentiation | 2 ** 8 is 256 |
Typed Array Functions
These functions operate on TypedArrays (Float64Array, Int32Array, etc.) for high-performance numeric computation. They are designed for use with the @fast decorator (see Performance).
typed_sum
typed_sum(arr) -> FloatComputes the sum using Kahan compensated summation, which minimizes floating-point error accumulation:
@fast fn precise_total(data: [Float]) -> Float {
typed_sum(data)
}typed_dot
typed_dot(a, b) -> FloatComputes the dot product of two arrays:
@fast fn dot(a: [Float], b: [Float]) -> Float {
typed_dot(a, b)
}typed_norm
typed_norm(arr) -> FloatComputes the L2 (Euclidean) norm of an array.
typed_add
typed_add(a, b) -> TypedArrayReturns a new typed array with element-wise addition of a and b.
typed_scale
typed_scale(arr, scalar) -> TypedArrayReturns a new typed array with every element multiplied by scalar.
typed_map
typed_map(arr, f) -> TypedArrayApplies f to each element, returning a new typed array of the same type.
typed_reduce
typed_reduce(arr, f, init) -> TReduces the typed array with function f and initial value init.
typed_sort
typed_sort(arr) -> TypedArrayReturns a new sorted typed array.
typed_zeros
typed_zeros(n) -> Float64ArrayCreates a Float64Array of n zeros.
typed_ones
typed_ones(n) -> Float64ArrayCreates a Float64Array of n ones.
typed_fill
typed_fill(arr, value) -> TypedArrayReturns a new typed array of the same type filled with value.
typed_range
typed_range(start, end, step) -> Float64ArrayCreates a Float64Array with values from start to end (exclusive), incrementing by step.
typed_linspace
typed_linspace(start, end, n) -> Float64ArrayCreates a Float64Array of n evenly-spaced values from start to end (inclusive).
Pipeline Examples
// Normalize scores to 0-100 range
scores
|> map(fn(s) clamp(s, 0, 100))
|> sorted()
// Generate random sample
range(10)
|> map(fn(_) random_int(0, 99))
|> sorted()
// Distance between two 2D points
fn distance(x1, y1, x2, y2) {
sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
}
// Statistical summary
data = [12, 15, 18, 22, 29, 34, 41]
print("Mean: {mean(data)}")
print("Median: {median(data)}")
print("Stdev: {stdev(data)}")
print("P90: {percentile(data, 90)}")