# knotkit/distribution

> Computes probabilities, quantiles, moments, and seeded draws for named and caller-defined distributions

## Use

```ts
import { Probability, poissonDistribution } from 'knotkit/distribution'
import { splitmix32 } from 'knotkit/prng'

const calls = poissonDistribution({ mean: 3 })
const atMostFive = calls.cumulativeProbability(5)
const firstCutoff = calls.quantile(atMostFive)
const percentile95 = calls.quantile(Probability.make(0.95))
const nextCount = calls.draw(splitmix32(20261119))
```

## What it solves

* compute probability below a threshold in a named distribution
* find a quantile for a distribution
* draw values from an injected source according to a distribution
* summarize observed numbers with a mean, variance, quantile, histogram, or correlation

## Choose a layout

| Factory                                                | Choose when                                                                                                                                           | Cost                                                               |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| `poissonDistribution`kind `poisson`                    | The quantity is a count of independent events at a known mean rate.                                                                                   | Probability tails use a regularized incomplete gamma function.     |
| `binomialDistribution`kind `binomial`                  | The quantity is successes in a fixed number of independent trials with one success probability.                                                       | Probability tails use a regularized incomplete beta function.      |
| `geometricDistribution`kind `geometric`                | The quantity is failures before the first success in independent trials.                                                                              | Mass, tails and a quantile estimate have closed forms.             |
| `hypergeometricDistribution`kind `hypergeometric`      | The quantity is successes in a sample drawn without replacement from a finite population.                                                             | Tail evaluation sums ratios of adjacent masses.                    |
| `normalDistribution`kind `normal`                      | The quantity is modeled as a symmetric bell-shaped real value.                                                                                        | Direct normal tails and inverse transform.                         |
| `logNormalDistribution`kind `log-normal`               | The quantity is positive and its natural logarithm follows a normal distribution.                                                                     | Normal tails in logarithmic coordinates.                           |
| `gammaDistribution`kind `gamma`                        | The quantity is a positive waiting time with a known gamma shape and rate.                                                                            | Incomplete-gamma tails and a bracketed quantile.                   |
| `exponentialDistribution`kind `exponential`            | The quantity is a memoryless waiting time at a known rate.                                                                                            | Closed-form tails and quantile.                                    |
| `chiSquaredDistribution`kind `chi-squared`             | The quantity is a sum of squared standard normals or a chi-squared test statistic.                                                                    | Gamma with rate one half.                                          |
| `betaDistribution`kind `beta`                          | The quantity is a continuous proportion on the unit interval with two shape parameters.                                                               | Incomplete-beta tails and a bracketed quantile.                    |
| `studentTDistribution`kind `student-t`                 | The quantity is a standardized mean of a normal sample whose variance is estimated, or a real value with heavier tails than normal.                   | Incomplete-beta tails and a bracketed quantile.                    |
| `fDistribution`kind `f`                                | The quantity is a ratio of two independent chi-squared variables each divided by its degrees of freedom, such as a variance ratio or ANOVA statistic. | Incomplete-beta tails and a bracketed quantile.                    |
| `uniformDistribution`kind `uniform`                    | The quantity is equally dense throughout a finite interval.                                                                                           | Closed-form tails and quantile.                                    |
| `probabilityTableDistribution`kind `probability-table` | The caller has an ordered table of finite values with explicit masses.                                                                                | O(n) preprocessing and O(log n) lookup and draw.                   |
| `customDiscreteDistribution`kind `custom-discrete`     | The caller supplies a mass function over integer outcomes and a CDF for unbounded upper support.                                                      | Finite tails sum masses; inversion brackets and searches integers. |
| `customContinuousDistribution`kind `custom-continuous` | The caller supplies the density and CDF for a continuous distribution over an interval.                                                               | Uses the supplied quantile or solves the bracketed inverse.        |

[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/distribution/README.md#performance)

## Try it

* Draw 10 times from a population containing 6 successes out of 20.
* Variance with replacement: 2.10. Without replacement: 1.11.
* Without replacement, the success count is more concentrated around 3.

Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/distribution/demo.ts) against `knotkit/distribution`.

## API

| Export                                                                                                    | Returns                        | Does                                                                                    |
| --------------------------------------------------------------------------------------------------------- | ------------------------------ | --------------------------------------------------------------------------------------- |
| [`poissonDistribution`](/reference/knotkit/distribution/functions/poissondistribution/)                   | `PoissonDistribution`          | A nonnegative finite mean defines the distribution.                                     |
| [`binomialDistribution`](/reference/knotkit/distribution/functions/binomialdistribution/)                 | `BinomialDistribution`         | Construct successProbability with Probability.make.                                     |
| [`geometricDistribution`](/reference/knotkit/distribution/functions/geometricdistribution/)               | `GeometricDistribution`        | Construct successProbability with Probability.make.                                     |
| [`hypergeometricDistribution`](/reference/knotkit/distribution/functions/hypergeometricdistribution/)     | `HypergeometricDistribution`   | Population, success count and sample size fix the distribution.                         |
| [`normalDistribution`](/reference/knotkit/distribution/functions/normaldistribution/)                     | `NormalDistribution`           | Location and standard deviation define the real-valued distribution.                    |
| [`logNormalDistribution`](/reference/knotkit/distribution/functions/lognormaldistribution/)               | `LogNormalDistribution`        | Parameters describe the natural logarithm of the quantity.                              |
| [`gammaDistribution`](/reference/knotkit/distribution/functions/gammadistribution/)                       | `GammaDistribution`            | Rate is the reciprocal of scale.                                                        |
| [`exponentialDistribution`](/reference/knotkit/distribution/functions/exponentialdistribution/)           | `ExponentialDistribution`      | Rate is the reciprocal of the mean.                                                     |
| [`chiSquaredDistribution`](/reference/knotkit/distribution/functions/chisquareddistribution/)             | `ChiSquaredDistribution`       | Degrees of freedom determine the shape.                                                 |
| [`betaDistribution`](/reference/knotkit/distribution/functions/betadistribution/)                         | `BetaDistribution`             | Alpha and beta define the bounded distribution.                                         |
| [`studentTDistribution`](/reference/knotkit/distribution/functions/studenttdistribution/)                 | `StudentTDistribution`         | Degrees of freedom define the heavy-tailed real-valued distribution.                    |
| [`fDistribution`](/reference/knotkit/distribution/functions/fdistribution/)                               | `FDistribution`                | Numerator and denominator degrees of freedom define the nonnegative ratio distribution. |
| [`uniformDistribution`](/reference/knotkit/distribution/functions/uniformdistribution/)                   | `UniformDistribution`          | Two ordered finite bounds define the interval.                                          |
| [`probabilityTableDistribution`](/reference/knotkit/distribution/functions/probabilitytabledistribution/) | `ProbabilityTableDistribution` | Construct the probability array with Probability.make.                                  |
| [`customDiscreteDistribution`](/reference/knotkit/distribution/functions/customdiscretedistribution/)     | `CustomDiscreteDistribution`   | Evaluates a caller-provided mass function.                                              |
| [`customContinuousDistribution`](/reference/knotkit/distribution/functions/customcontinuousdistribution/) | `CustomContinuousDistribution` | Uses an optional caller-supplied survival function and quantile.                        |
| [`sampleMean`](/reference/knotkit/distribution/functions/samplemean/)                                     | `number`                       | Running arithmetic mean of a finite sample.                                             |
| [`sampleVariance`](/reference/knotkit/distribution/functions/samplevariance/)                             | `number`                       | Welford variance; degreesOfFreedomCorrection defaults to 1.                             |
| [`median`](/reference/knotkit/distribution/functions/median/)                                             | `number`                       | Exact median of a sorted copy.                                                          |
| [`sampleQuantile`](/reference/knotkit/distribution/functions/samplequantile/)                             | `number`                       | Type 7 linear-interpolation quantile of a sorted copy.                                  |
| [`histogram`](/reference/knotkit/distribution/functions/histogram/)                                       | `Histogram`                    | Counts per half-open bin, last bin closed, as np.histogram.                             |
| [`covariance`](/reference/knotkit/distribution/functions/covariance/)                                     | `number`                       | Welford co-moment covariance; degreesOfFreedomCorrection defaults to 1.                 |
| [`pearsonCorrelation`](/reference/knotkit/distribution/functions/pearsoncorrelation/)                     | `number`                       | Product-moment correlation clamped to \[-1, 1].                                         |

Cost per member. Open a row for every operation.

`sampleMean` 1 members

| Member    | Cost      |
| --------- | --------- |
| `compare` | O(n) time |

`sampleVariance` 1 members

| Member    | Cost      |
| --------- | --------- |
| `compare` | O(n) time |

`median` 1 members

| Member    | Cost                                 |
| --------- | ------------------------------------ |
| `compare` | O(n log n) time and O(n) extra space |

`sampleQuantile` 1 members

| Member    | Cost                                 |
| --------- | ------------------------------------ |
| `compare` | O(n log n) time and O(n) extra space |

`histogram` 1 members

| Member    | Cost                      |
| --------- | ------------------------- |
| `compare` | O(n log n + n log k) time |

`covariance` 1 members

| Member    | Cost      |
| --------- | --------- |
| `compare` | O(n) time |

`pearsonCorrelation` 1 members

| Member    | Cost      |
| --------- | --------- |
| `compare` | O(n) time |

## What you pass in

| Input                                          | Type                                                                             | Get one from                     |
| ---------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------- |
| randomness per draw                            | `RandomSource`                                                                   | [`knotkit/prng`](/modules/prng/) |
| probability callbacks for custom distributions | `CustomDiscreteDistributionParameters or CustomContinuousDistributionParameters` | `caller`                         |

## Errors

Every error this module throws is `DistributionInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.

* `DistributionInvalidInputError`

  `INVALID_PARAMETER` `INVALID_PROBABILITY` `INVALID_TABLE` `INVALID_SAMPLE` `ZERO_VARIANCE`

* `Other`

  `INVALID_ARGUMENT` `INVALID_MOMENT_ORDER` `INVALID_CALLBACK_VALUE` `QUANTILE_NOT_BRACKETED`

## When not to use it

| If you need to…                         | Use instead                                            |
| --------------------------------------- | ------------------------------------------------------ |
| shuffle or sample from an array         | [`knotkit/sampling`](/modules/sampling/)               |
| fit a distribution's parameters to data | SciPy or R                                             |
| test whether draws fit a distribution   | [`knotkit/hypothesis-test`](/modules/hypothesis-test/) |
| evaluate a multivariate distribution    | SciPy or R                                             |

## Performance

Measured by the suite in [`packages/distribution/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/distribution/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/distributionCopy prompt

```
Use knotkit/distribution for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/distribution'.

Exports:
- `poissonDistribution` → `PoissonDistribution`: A nonnegative finite mean defines the distribution.
- `binomialDistribution` → `BinomialDistribution`: Construct successProbability with Probability.make.
- `geometricDistribution` → `GeometricDistribution`: Construct successProbability with Probability.make.
- `hypergeometricDistribution` → `HypergeometricDistribution`: Population, success count and sample size fix the distribution.
- `normalDistribution` → `NormalDistribution`: Location and standard deviation define the real-valued distribution.
- `logNormalDistribution` → `LogNormalDistribution`: Parameters describe the natural logarithm of the quantity.
- `gammaDistribution` → `GammaDistribution`: Rate is the reciprocal of scale.
- `exponentialDistribution` → `ExponentialDistribution`: Rate is the reciprocal of the mean.
- `chiSquaredDistribution` → `ChiSquaredDistribution`: Degrees of freedom determine the shape.
- `betaDistribution` → `BetaDistribution`: Alpha and beta define the bounded distribution.
- `studentTDistribution` → `StudentTDistribution`: Degrees of freedom define the heavy-tailed real-valued distribution.
- `fDistribution` → `FDistribution`: Numerator and denominator degrees of freedom define the nonnegative ratio distribution.
- `uniformDistribution` → `UniformDistribution`: Two ordered finite bounds define the interval.
- `probabilityTableDistribution` → `ProbabilityTableDistribution`: Construct the probability array with Probability.make.
- `customDiscreteDistribution` → `CustomDiscreteDistribution`: Evaluates a caller-provided mass function.
- `customContinuousDistribution` → `CustomContinuousDistribution`: Uses an optional caller-supplied survival function and quantile.
- `sampleMean` → `number`: Running arithmetic mean of a finite sample.
- `sampleVariance` → `number`: Welford variance; degreesOfFreedomCorrection defaults to 1.
- `median` → `number`: Exact median of a sorted copy.
- `sampleQuantile` → `number`: Type 7 linear-interpolation quantile of a sorted copy.
- `histogram` → `Histogram`: Counts per half-open bin, last bin closed, as np.histogram.
- `covariance` → `number`: Welford co-moment covariance; degreesOfFreedomCorrection defaults to 1.
- `pearsonCorrelation` → `number`: Product-moment correlation clamped to [-1, 1].

Pick the layout by these rules:
- `poissonDistribution` (kind 'poisson') when The quantity is a count of independent events at a known mean rate.
- `binomialDistribution` (kind 'binomial') when The quantity is successes in a fixed number of independent trials with one success probability.
- `geometricDistribution` (kind 'geometric') when The quantity is failures before the first success in independent trials.
- `hypergeometricDistribution` (kind 'hypergeometric') when The quantity is successes in a sample drawn without replacement from a finite population.
- `normalDistribution` (kind 'normal') when The quantity is modeled as a symmetric bell-shaped real value.
- `logNormalDistribution` (kind 'log-normal') when The quantity is positive and its natural logarithm follows a normal distribution.
- `gammaDistribution` (kind 'gamma') when The quantity is a positive waiting time with a known gamma shape and rate.
- `exponentialDistribution` (kind 'exponential') when The quantity is a memoryless waiting time at a known rate.
- `chiSquaredDistribution` (kind 'chi-squared') when The quantity is a sum of squared standard normals or a chi-squared test statistic.
- `betaDistribution` (kind 'beta') when The quantity is a continuous proportion on the unit interval with two shape parameters.
- `studentTDistribution` (kind 'student-t') when The quantity is a standardized mean of a normal sample whose variance is estimated, or a real value with heavier tails than normal.
- `fDistribution` (kind 'f') when The quantity is a ratio of two independent chi-squared variables each divided by its degrees of freedom, such as a variance ratio or ANOVA statistic.
- `uniformDistribution` (kind 'uniform') when The quantity is equally dense throughout a finite interval.
- `probabilityTableDistribution` (kind 'probability-table') when The caller has an ordered table of finite values with explicit masses.
- `customDiscreteDistribution` (kind 'custom-discrete') when The caller supplies a mass function over integer outcomes and a CDF for unbounded upper support.
- `customContinuousDistribution` (kind 'custom-continuous') when The caller supplies the density and CDF for a continuous distribution over an interval.

Inputs and their sources:
- randomness per draw: `RandomSource` from `knotkit/prng`
- probability callbacks for custom distributions: `CustomDiscreteDistributionParameters or CustomContinuousDistributionParameters` from `caller`

Use something else when:
- shuffle or sample from an array → knotkit/sampling
- fit a distribution's parameters to data → SciPy or R
- test whether draws fit a distribution → knotkit/hypothesis-test
- evaluate a multivariate distribution → SciPy or R

Errors are DistributionInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/distribution.md
Types: node_modules/knotkit/distribution/ and https://knotkit.jkomyno.dev/reference/knotkit/distribution/
```

## See also

* [API reference](/reference/knotkit/distribution/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/distribution/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/distribution/knotkit.capability.json)suggest a change to the source record
