fn histquantile_max2(a: f64, b: f64) -> f64 { if a > b { return a; } b } fn histquantile_ceilpos(value: f64) -> f64 { let rest = value % 1.0; if rest > 0.0 { return value - rest + 1.0; } value } fn histquantile_finite(values: vector) -> bool { let mut i = 0; while i < len(values) { let value = at(values, i); if !(value - value == 0.0) { return false; } i += 1; } true } fn histquantile_counts(values: vector) -> bool { let mut i = 0; while i < len(values) { let value = at(values, i); if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) { return false; } i += 1; } true } fn histquantile_compute(counts: vector, probability: f64) -> vector { let total = sum(counts); if total <= 0.0 || total > 9007199254740991.0 { return []; } let rank = histquantile_max2(1.0, histquantile_ceilpos(total * probability)); let mut seen = 0.0; let mut i = 0; while i < len(counts) { seen += at(counts, i); if seen >= rank { return [i, rank, total]; } i += 1; } [] } // Locate a nearest-rank quantile in noncumulative histogram counts. // Returns [bucket index, one-based rank, total observations]. At probability zero select the first occupied bucket. Empty histograms are invalid. pub fn histquantile_bucket(counts: vector, probability: f64) -> vector { if !histquantile_counts(counts) { return []; } if !(probability >= 0.0 && probability <= 1.0) { return []; } let result = histquantile_compute(counts, probability); if !histquantile_finite(result) { return []; } result }