code wiki / (root) / sketch_moments.nx

sketch_moments.nx

buildroot/runtime/sketch_moments.nx

6919 B216 linesdepth 5pulls 5 transitivereach 1 importersview sourcekind sketch/demotopic sketch
docsdependenciesstructsconstsfunctions

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

syscalls.nx sketch_stream_stats.nx sketch_types.nx sketch_moments.nx sketch_moments_test.nx

imports: syscalls.nxsketch_stream_stats.nxsketch_types.nx

imported by: sketch_moments_test.nx

structs

40struct Moments {

consts

38const NX_MOM_X_LIMIT: i64 = 2048 // |x| < 2^11 for safe x^4

functions

50func nx_mom_alloc() -> *Moments {
called by 2: nx_mom_mergemain
63func nx_mom_safe_p(value: i64) -> i64 {
called by 2: nx_mom_addmain
72func nx_mom_add(m: *Moments, value: i64) -> i64 {
called by 1: main calls 1: nx_mom_safe_p
87func nx_mom_mean(m: *Moments) -> i64 {
92func nx_mom_variance(m: *Moments) -> i64 {
102func nx_mom_m3(m: *Moments) -> i64 {
called by 1: nx_mom_skewness_ppm calls 1: nx_mom_mean
112func nx_mom_m4(m: *Moments) -> i64 {
called by 1: nx_mom_kurtosis_ppm calls 1: nx_mom_mean
128func nx_mom_isqrt(x: i64) -> i64 {
145func nx_mom_skewness_ppm(m: *Moments) -> i64 {
156func nx_mom_kurtosis_ppm(m: *Moments) -> i64 {
175func nx_mom_stderr_ppb(count: i64) -> i64 {
182func nx_mom_query_skewness(m: *Moments) -> *ApproxI64 {
191func nx_mom_query_kurtosis(m: *Moments) -> *ApproxI64 {
204func nx_mom_merge(a: *Moments, b: *Moments) -> *Moments {
called by 1: main calls 1: nx_mom_alloc
214func nx_mom_memory_bytes(m: *Moments) -> i64 {