NAME
    Statistics::CaseResampling - Efficient resampling and calculation of
    medians with confidence intervals

SYNOPSIS
      use Statistics::CaseResampling ':all';
  
      my $sample = [1,3,5,7,1,2,9,4,6,8]; # ... usually MUCH more data ...
      my $confidence = 0.95; # 95% confidence limits (~1.96*sigma)
      #my $confidence = 1 - nsigma_to_alpha(1); # ~1*sigma (~68.27% confidence limits)
  
      # calculate the median of the sample with distribution-free exact
      # binomial confidence limits:
      my ($lower_cl, $median, $upper_cl)
        = median_exact_confidence_limits($sample, $confidence);
  
      # or using percentile bootstrapping (defaults to 1000 resamples; use
      # 5000-10000+ for reliable tail limits):
      my ($lower_cl_boot, $median_boot, $upper_cl_boot)
        = median_percentile_confidence_limits($sample, $confidence, 5000);
  
      # There are many auxiliary functions:
  
      my $resampled = resample($sample);
      # $resampled is now a random set of measurements from $sample,
      # including potential duplicates
  
      my $medians = resample_medians($sample, $n_resamples);
      # $medians is now an array reference containing the medians
      # of $n_resamples resample runs
      # This is vastly more efficient than doing the same thing with
      # repeated resample() calls!
      # Analogously:
      my $means = resample_means($sample, $n_resamples);
  
      # you can get two-sided percentile (or basic, or BCa) confidence limits
      # from a set of separately resampled statistics, too:
      my ($lower_m, $mean, $upper_m)
        = percentile_confidence_limits_from_samples(mean($sample), $means, $confidence);
  
      # utility functions:
      print median([1..5]), "\n"; # prints 3
      print mean([1..5]), "\n"; # prints 3, too, surprise!
      print quantile([1..4], 0.5), "\n"; # prints 2.5
      print select_kth([1..5], 1), "\n"; # inefficient way to calculate the minimum

DESCRIPTION
    The purpose of this (XS) module is to calculate the median (or in
    principle also other statistics) with confidence intervals on a sample.
    To do that, it uses a technique called bootstrapping. In a nutshell, it
    resamples the sample a lot of times and for each resample, it calculates
    the statistic. From the distribution of resampled statistics, it then
    calculates the confidence limits.

    In order to implement the confidence limit calculation, various other
    functions had to be implemented efficiently (both algorithmically
    efficient and done in C). These functions may be useful in their own
    right and are thus exposed to Perl. Most notably, this exposes a median
    (and general selection) algorithm that works in linear time as opposed
    to the trivial implementation that requires "O(n*log(n))".

  Statistical caveats
    Case resampling (nonparametric bootstrap) assumes that the observations
    in $sample are independent and identically distributed (i.i.d.). If your
    data exhibits autocorrelation, time trends, or clustering, standard case
    resampling will underestimate uncertainty.

    Additionally, bootstrap confidence intervals for the median have limited
    coverage accuracy on very small samples (e.g. "N < 15") or when the data
    contains many tied values; prefer
    "median_exact_confidence_limits(SAMPLE, CONFIDENCE)" when a
    distribution-free confidence interval for the median is required.

  Random numbers
    The resampling involves drawing many random numbers. Therefore, the
    module comes with an embedded Mersenne twister (taken from
    "Math::Random::MT").

    If you want to change the seed of the RNG, do this:

      $Statistics::CaseResampling::Rnd
        = Statistics::CaseResampling::RdGen::setup($seed);

    or

      $Statistics::CaseResampling::Rnd
        = Statistics::CaseResampling::RdGen::setup_array(@seed);

    The default module RNG is automatically seeded from native OS entropy
    ("BCryptGenRandom"/"RtlGenRandom" on Windows, "/dev/urandom" on Unix, or
    process/time/PRNG fallback state when unavailable) and is reseeded
    across "ithreads" cloning and fork(). Explicitly seeded RNG objects
    retain their exact deterministic sequence.

    Do not use the embedded random number generator for other purposes. Use
    "Math::Random::MT" instead! At this point, you cannot change the type of
    RNG.

  EXPORT
    None by default.

    Can export any of the functions that are documented below using standard
    "Exporter" semantics, including the customary ":all" group.

FUNCTIONS
    This list of functions is loosely sorted from *basic* to *comprehensive*
    because the more complicated functions are usually (under the hood, in
    C) implemented using the basic building blocks. Unfortunately, that
    means you may want to read the documentation backwards. :)

    All of these functions are written in C for speed.

  resample(ARRAYREF)
    Returns a reference to an array containing N random elements from the
    input array, where N is the length of the original array.

    This is different from shuffling in that it's random drawing without
    removing the drawn elements from the sample.

  resample_medians(ARRAYREF, NMEDIANS)
    Returns a reference to an array containing the medians of "NMEDIANS"
    resamples of the original input sample.

  resample_means(ARRAYREF, NMEANS)
    Returns a reference to an array containing the means of "NMEANS"
    resamples of the original input sample.

  percentile_confidence_limits_from_samples(STATISTIC, STATISTIC_SAMPLES, CONFIDENCE)
    Calculates two-sided percentile bootstrap confidence limits at level
    *CONFIDENCE* (in "(0, 1)") using linear quantile interpolation at
    "alpha/2" and "1 - alpha/2", where "alpha = 1 - CONFIDENCE". Returns
    "($lower_cl, $statistic, $upper_cl)".

    For example, to get a 95% confidence interval for the mean of your
    sample:

      my $sample = [<numbers>];
      my $means = resample_means($sample, 5000);
      my ($lower_cl, $mean, $upper_cl)
        = percentile_confidence_limits_from_samples(mean($sample), $means, 0.95);

    For reliable tail limits at 95% or higher confidence, use at least
    5000-10000 bootstrap samples.

  basic_confidence_limits_from_samples(STATISTIC, STATISTIC_SAMPLES, CONFIDENCE)
    Calculates two-sided basic (pivotal) bootstrap confidence limits at
    level *CONFIDENCE* (in "(0, 1)") as "2 * STATISTIC -
    quantile(STATISTIC_SAMPLES, 1 - alpha/2)" and "2 * STATISTIC -
    quantile(STATISTIC_SAMPLES, alpha/2)", where "alpha = 1 - CONFIDENCE".
    Returns "($lower_cl, $statistic, $upper_cl)".

    Note that for heavily skewed distributions or bounded statistics (e.g.
    strictly positive measurements), the basic bootstrap reflection can
    produce limits outside the parameter support; prefer
    "percentile_confidence_limits_from_samples(STATISTIC, STATISTIC_SAMPLES,
    CONFIDENCE)" or "bca_confidence_limits_from_samples(STATISTIC,
    STATISTIC_SAMPLES, JACKKNIFE_SAMPLES, CONFIDENCE)" in those cases.

  bca_confidence_limits_from_samples(STATISTIC, STATISTIC_SAMPLES, JACKKNIFE_SAMPLES, CONFIDENCE)
    Calculates two-sided bias-corrected and accelerated (BCa) bootstrap
    confidence limits at level *CONFIDENCE* (in "(0, 1)").
    *JACKKNIFE_SAMPLES* must be an array reference of leave-one-out
    jackknife estimates of the statistic on the original sample. Returns
    "($lower_cl, $statistic, $upper_cl)".

    BCa intervals correct for both median bias and skewness (via the
    acceleration constant) and are transformation-respecting.

  median_percentile_confidence_limits(SAMPLE, CONFIDENCE, [NSAMPLES])
    Calculates two-sided percentile bootstrap confidence limits for the
    exact median (interpolated at "p = 0.5" for even sample sizes) of
    *SAMPLE*. *NSAMPLES* defaults to 1000 (use 5000 or more for stable 95%+
    limits). Returns "($lower_cl, $median, $upper_cl)".

  median_exact_confidence_limits(SAMPLE, CONFIDENCE)
    Calculates exact distribution-free confidence limits for the median of
    *SAMPLE* using the symmetric binomial distribution "Binomial(n, 0.5)" on
    the order statistics, returning "($lower_cl, $median, $upper_cl)" with
    at least *CONFIDENCE* coverage (assuming continuous i.i.d.
    observations). This requires no Monte Carlo resampling and runs in O(n)
    time.

  simple_confidence_limits_from_samples(STATISTIC, STATISTIC_SAMPLES, CONFIDENCE)
    Legacy basic-bootstrap confidence limit calculation retained for
    backward compatibility. Returns "($lower_cl, $statistic, $upper_cl)".

    Note: For historical compatibility, this function uses one-tailed
    indexing with "alpha = 1 - CONFIDENCE" in each tail rather than
    "alpha/2", so "CONFIDENCE = 0.95" corresponds to a 90% two-sided
    interval and "CONFIDENCE < 0.5" produces inverted limits. New code
    should use "basic_confidence_limits_from_samples(STATISTIC,
    STATISTIC_SAMPLES, CONFIDENCE)",
    "percentile_confidence_limits_from_samples(STATISTIC, STATISTIC_SAMPLES,
    CONFIDENCE)", or "bca_confidence_limits_from_samples(STATISTIC,
    STATISTIC_SAMPLES, JACKKNIFE_SAMPLES, CONFIDENCE)".

    For example:

      my $sample = [<numbers>];
      my $means = resample_means($sample, 5000);
      my ($lower_cl, $mean, $upper_cl)
        = simple_confidence_limits_from_samples(mean($sample), $means, 0.95);

    If you want to apply this logic to other statistics such as the first or
    third quartile, you have to manually resample and lose the advantage of
    doing it in C:

      my $sample = [<numbers>];
      my $quartiles = [];
      foreach (1..5000) {
        push @$quartiles, first_quartile(resample($sample));
      }
      my ($lower_cl, $firstq, $upper_cl)
        = percentile_confidence_limits_from_samples(
            first_quartile($sample), $quartiles, 0.95
          );

    For medians, however, use "median_exact_confidence_limits(SAMPLE,
    CONFIDENCE)" or "median_percentile_confidence_limits(SAMPLE, CONFIDENCE,
    [NSAMPLES])".

  median_simple_confidence_limits(SAMPLE, CONFIDENCE, [NSAMPLES])
    Legacy basic-bootstrap confidence limits for the median retained for
    backward compatibility. Returns the lower confidence limit, the median,
    and the upper confidence limit. *NSAMPLES* defaults to 1000.

    Like "simple_confidence_limits_from_samples", this uses one-tailed
    "alpha = 1 - CONFIDENCE" indexing in each tail. New code should prefer
    "median_exact_confidence_limits(SAMPLE, CONFIDENCE)" or
    "median_percentile_confidence_limits(SAMPLE, CONFIDENCE, [NSAMPLES])".

OTHER FUNCTIONS
  approx_erf($x)
    Calculates the error function of *x* (using the C math library erf()
    where available, with a high-precision fallback otherwise).

  approx_erf_inv($x)
    Calculates the inverse of the error function of *x* for *x* in "(0, 1)"
    to near machine precision.

  nsigma_to_alpha($nsigma)
    Calculates the two-sided probability "erfc($nsigma / sqrt(2))" that a
    measurement from a normal distribution is further away from the mean
    than $nsigma standard deviations.

    The two-sided confidence level is "1 - nsigma_to_alpha($nsigma)".

  alpha_to_nsigma($alpha)
    Inverse of nsigma_to_alpha().

  mean(ARRAYREF)
    Calculates the arithmetic mean of a sample using compensated summation
    (and overflow-safe scaling for extreme magnitudes).

  quantile(ARRAYREF, P)
    Calculates the sample quantile for probability *P* in "[0, 1]" in O(n)
    expected time using Hyndman-Fan Type 7 linear interpolation (the default
    in R, NumPy, and Julia). At "P = 0.5", this computes the exact median,
    averaging the two middle elements when N is even.

  median(ARRAYREF)
    Calculates the median (second quartile) of a sample. Works in linear
    time thanks to using a selection instead of a sort.

    For historical backward compatibility, the median of an even number of
    elements is defined as the (0-based) "n/2 - 1"th smallest number rather
    than the average of the two middle elements. Use "quantile($sample,
    0.5)" if you want the exact averaged median for even sample sizes.

  median_absolute_deviation(ARRAYREF)
    Calculates the median absolute deviation (MAD) in O(n) expected time.
    Note that for consistency with a normal standard deviation, a normally
    distributed sample requires rescaling by "1 / (sqrt(2) * erfinv(0.5))"
    (approximately 1.4826).

  first_quartile(ARRAYREF)
    Calculates the first quartile of the sample (legacy 0-based index
    int(n/4)). For Type 7 interpolated quartiles, use "quantile($sample,
    0.25)".

  third_quartile(ARRAYREF)
    Calculates the third quartile of the sample (legacy 0-based index
    int(3*n/4)). For Type 7 interpolated quartiles, use "quantile($sample,
    0.75)".

  select_kth(ARRAYREF, K)
    Selects the kth smallest element (1-based) from the sample.

    This is the general function that implements the median/quartile
    calculation. You get the legacy median with this definition of K:

      my $k = int(@$sample/2) + (@$sample & 1);
      my $median = select_kth($sample, $k);

  sample_standard_deviation([$mean,] ARRAYREF)
    Calculates the sample standard deviation (with Bessel's "N - 1"
    correction). May be called with either "(\@sample)" (computing the
    sample mean automatically) or "($mean, \@sample)". Note that Bessel's "N
    - 1" denominator is only statistically appropriate when $mean is the
    sample mean of @sample.

  population_standard_deviation([$mean,] ARRAYREF)
    Same as "sample_standard_deviation", but dividing by "N" instead of "N -
    1". May be called as "(\@sample)" or "($mean, \@sample)".

TODO
    One could calculate more statistics in C for performance.

SEE ALSO
    Math::Random::MT

    The ~O(n) median implementation is based on C.A.R. Hoare's quickselect
    algorithm. See
    <http://en.wikipedia.org/wiki/Selection_algorithm#Partition-based_genera
    l_selection_algorithm>. Right now, it does not implement the Median of
    Medians algorithm that would guarantee linearity.

AUTHOR
    Steffen Mueller, <cpan@steffen-mueller.net>

    Daniel Dragan, <bulk88@hotmail.com>, who supplied MSVC compatibility
    patches.

COPYRIGHT AND LICENSE
    Copyright (C) 2010, 2011, 2012, 2013, 2025, 2026 by Steffen Mueller

    This library is free software; you can redistribute it and/or modify it
    under the same terms as Perl itself, either Perl version 5.8.0 or, at
    your option, any later version of Perl 5 you may have available.

