sketch_moments.nx
buildroot/runtime/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 · 1 importers
imports: syscalls.nxsketch_stream_stats.nxsketch_types.nx
imported by: sketch_moments_test.nx
structs
| 40 | struct Moments { |
consts
| 38 | const NX_MOM_X_LIMIT: i64 = 2048 // |x| < 2^11 for safe x^4 |
functions
| 50 | func nx_mom_alloc() -> *Moments { |
| 63 | func nx_mom_safe_p(value: i64) -> i64 { |
| 72 | func nx_mom_add(m: *Moments, value: i64) -> i64 { |
| 87 | func nx_mom_mean(m: *Moments) -> i64 { |
| 92 | func nx_mom_variance(m: *Moments) -> i64 { |
| 102 | func nx_mom_m3(m: *Moments) -> i64 { |
| 112 | func nx_mom_m4(m: *Moments) -> i64 { |
| 128 | func nx_mom_isqrt(x: i64) -> i64 { |
| 145 | func nx_mom_skewness_ppm(m: *Moments) -> i64 { |
| 156 | func nx_mom_kurtosis_ppm(m: *Moments) -> i64 { |
| 175 | func nx_mom_stderr_ppb(count: i64) -> i64 { |
| 182 | func nx_mom_query_skewness(m: *Moments) -> *ApproxI64 { |
| 191 | func nx_mom_query_kurtosis(m: *Moments) -> *ApproxI64 { |
| 204 | func nx_mom_merge(a: *Moments, b: *Moments) -> *Moments { |
| 214 | func nx_mom_memory_bytes(m: *Moments) -> i64 { |