nx_sketch_moments.nx
buildroot/runtime/nx_sketch_moments.nx
about
sketch_moments.nx -- streaming higher moments (skewness + kurtosis).
Extends sketch_stream_stats with 3rd and 4th central moments via a
naive cumulative-power approach:
sum_x = Σ x_i
sum_x2 = Σ x_i²
sum_x3 = Σ x_i³
sum_x4 = Σ x_i⁴
From these, central moments via the algebraic identities:
mean = sum_x / n
var = sum_x2/n - mean²
m3 = sum_x3/n - 3·mean·var - mean³ (third central)
m4 = sum_x4/n - 4·mean·(sum_x3/n) + 6·mean²·(sum_x2/n) - 3·mean⁴
skewness = m3 / σ³ (Fisher-Pearson)
kurtosis = m4 / σ⁴ - 3 (excess kurtosis; normal distribution = 0)
OVERFLOW BUDGET (CRITICAL):
sum_x4 grows like n · |x|⁴. For |x| up to 2^16 and n up to 2^30,
sum_x4 < 2^30 · 2^64 → overflows i64 (which caps at 2^63).
Tight bound: n · |x|⁴ < 2^62. E.g. |x| <= 2^11 (~2K) and n <= 2^18 (~260K)
are safe. Caller responsibility. nx_mom_safe_p flags unsafe values.
FOR PROPER OBSERVABILITY ENGINEERING: use this with normalized /
quantized inputs (e.g. milliseconds with values < 2K, sample counts
< 100K). For broader ranges, use sketch_reservoir + caller-side
computation on the sample.
LOSSLESS-LANGUAGE DISCIPLINE: skewness/kurtosis envelope is
NX_ENV_REL_STDDEV with param_a ~ 1/sqrt(n) (standard error of
higher-moment estimators). Caller treats these as bounded-error
statistics over the integer-exact accumulators.
dependencies 3 imports · 0 importers
imports: nx_syscalls.nxnx_sketch_stream_stats.nxnx_sketch_types.nx
imported by: nobody (leaf or entry point)
structs
| 46 | struct Moments |
consts
| 44 | const NX_MOM_X_LIMIT: i64 = 2048 // |x| < 2^11 for safe x^4 |
functions
| 56 | func nx_mom_alloc() -> *Moments |
| 69 | func nx_mom_safe_p(value: i64) -> i64 called by 1: nx_mom_add |
| 78 | func nx_mom_add(m: *Moments, value: i64) -> i64 calls 1: nx_mom_safe_p |
| 93 | func nx_mom_mean(m: *Moments) -> i64 |
| 98 | func nx_mom_variance(m: *Moments) -> i64 |
| 108 | func nx_mom_m3(m: *Moments) -> i64 |
| 118 | func nx_mom_m4(m: *Moments) -> i64 |
| 134 | func nx_mom_isqrt(x: i64) -> i64 |
| 151 | func nx_mom_skewness_ppm(m: *Moments) -> i64 |
| 162 | func nx_mom_kurtosis_ppm(m: *Moments) -> i64 |
| 181 | func nx_mom_stderr_ppb(count: i64) -> i64 |
| 188 | func nx_mom_query_skewness(m: *Moments) -> *ApproxI64 |
| 197 | func nx_mom_query_kurtosis(m: *Moments) -> *ApproxI64 |
| 210 | func nx_mom_merge(a: *Moments, b: *Moments) -> *Moments calls 1: nx_mom_alloc |
| 220 | func nx_mom_memory_bytes(m: *Moments) -> i64 |