@ac-kit/math-stats 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +28 -0
  3. package/README.md +91 -0
  4. package/dist/_assert-probability.d.ts +14 -0
  5. package/dist/_assert-probability.d.ts.map +1 -0
  6. package/dist/_assert-probability.js +18 -0
  7. package/dist/_assert-probability.js.map +1 -0
  8. package/dist/_discrete-quantile.d.ts +16 -0
  9. package/dist/_discrete-quantile.d.ts.map +1 -0
  10. package/dist/_discrete-quantile.js +43 -0
  11. package/dist/_discrete-quantile.js.map +1 -0
  12. package/dist/_inverse-transform-sample.d.ts +17 -0
  13. package/dist/_inverse-transform-sample.d.ts.map +1 -0
  14. package/dist/_inverse-transform-sample.js +18 -0
  15. package/dist/_inverse-transform-sample.js.map +1 -0
  16. package/dist/_log-binomial.d.ts +16 -0
  17. package/dist/_log-binomial.d.ts.map +1 -0
  18. package/dist/_log-binomial.js +19 -0
  19. package/dist/_log-binomial.js.map +1 -0
  20. package/dist/average.d.ts +95 -0
  21. package/dist/average.d.ts.map +1 -0
  22. package/dist/average.js +113 -0
  23. package/dist/average.js.map +1 -0
  24. package/dist/beta-distribution.d.ts +15 -0
  25. package/dist/beta-distribution.d.ts.map +1 -0
  26. package/dist/beta-distribution.js +61 -0
  27. package/dist/beta-distribution.js.map +1 -0
  28. package/dist/binomial-distribution.d.ts +18 -0
  29. package/dist/binomial-distribution.d.ts.map +1 -0
  30. package/dist/binomial-distribution.js +74 -0
  31. package/dist/binomial-distribution.js.map +1 -0
  32. package/dist/chi-squared-distribution.d.ts +15 -0
  33. package/dist/chi-squared-distribution.d.ts.map +1 -0
  34. package/dist/chi-squared-distribution.js +25 -0
  35. package/dist/chi-squared-distribution.js.map +1 -0
  36. package/dist/chi-squared-test.d.ts +39 -0
  37. package/dist/chi-squared-test.d.ts.map +1 -0
  38. package/dist/chi-squared-test.js +56 -0
  39. package/dist/chi-squared-test.js.map +1 -0
  40. package/dist/confidence-interval.d.ts +62 -0
  41. package/dist/confidence-interval.d.ts.map +1 -0
  42. package/dist/confidence-interval.js +93 -0
  43. package/dist/confidence-interval.js.map +1 -0
  44. package/dist/dispersion.d.ts +45 -0
  45. package/dist/dispersion.d.ts.map +1 -0
  46. package/dist/dispersion.js +80 -0
  47. package/dist/dispersion.js.map +1 -0
  48. package/dist/distribution.d.ts +61 -0
  49. package/dist/distribution.d.ts.map +1 -0
  50. package/dist/distribution.js +2 -0
  51. package/dist/distribution.js.map +1 -0
  52. package/dist/exponential-distribution.d.ts +15 -0
  53. package/dist/exponential-distribution.d.ts.map +1 -0
  54. package/dist/exponential-distribution.js +33 -0
  55. package/dist/exponential-distribution.js.map +1 -0
  56. package/dist/f-distribution.d.ts +17 -0
  57. package/dist/f-distribution.d.ts.map +1 -0
  58. package/dist/f-distribution.js +88 -0
  59. package/dist/f-distribution.js.map +1 -0
  60. package/dist/gamma-distribution.d.ts +15 -0
  61. package/dist/gamma-distribution.d.ts.map +1 -0
  62. package/dist/gamma-distribution.js +45 -0
  63. package/dist/gamma-distribution.js.map +1 -0
  64. package/dist/geometric-distribution.d.ts +19 -0
  65. package/dist/geometric-distribution.d.ts.map +1 -0
  66. package/dist/geometric-distribution.js +54 -0
  67. package/dist/geometric-distribution.js.map +1 -0
  68. package/dist/hierarchical-cluster.d.ts +35 -0
  69. package/dist/hierarchical-cluster.d.ts.map +1 -0
  70. package/dist/hierarchical-cluster.js +97 -0
  71. package/dist/hierarchical-cluster.js.map +1 -0
  72. package/dist/hypergeometric-distribution.d.ts +18 -0
  73. package/dist/hypergeometric-distribution.d.ts.map +1 -0
  74. package/dist/hypergeometric-distribution.js +92 -0
  75. package/dist/hypergeometric-distribution.js.map +1 -0
  76. package/dist/index.d.ts +34 -0
  77. package/dist/index.d.ts.map +1 -0
  78. package/dist/index.js +34 -0
  79. package/dist/index.js.map +1 -0
  80. package/dist/kmeans.d.ts +87 -0
  81. package/dist/kmeans.d.ts.map +1 -0
  82. package/dist/kmeans.js +126 -0
  83. package/dist/kmeans.js.map +1 -0
  84. package/dist/kmedoids.d.ts +27 -0
  85. package/dist/kmedoids.d.ts.map +1 -0
  86. package/dist/kmedoids.js +47 -0
  87. package/dist/kmedoids.js.map +1 -0
  88. package/dist/log-normal-distribution.d.ts +15 -0
  89. package/dist/log-normal-distribution.d.ts.map +1 -0
  90. package/dist/log-normal-distribution.js +44 -0
  91. package/dist/log-normal-distribution.js.map +1 -0
  92. package/dist/negative-binomial-distribution.d.ts +18 -0
  93. package/dist/negative-binomial-distribution.d.ts.map +1 -0
  94. package/dist/negative-binomial-distribution.js +64 -0
  95. package/dist/negative-binomial-distribution.js.map +1 -0
  96. package/dist/normal-distribution.d.ts +16 -0
  97. package/dist/normal-distribution.d.ts.map +1 -0
  98. package/dist/normal-distribution.js +41 -0
  99. package/dist/normal-distribution.js.map +1 -0
  100. package/dist/normal-quantile.d.ts +19 -0
  101. package/dist/normal-quantile.d.ts.map +1 -0
  102. package/dist/normal-quantile.js +115 -0
  103. package/dist/normal-quantile.js.map +1 -0
  104. package/dist/one-way-anova.d.ts +31 -0
  105. package/dist/one-way-anova.d.ts.map +1 -0
  106. package/dist/one-way-anova.js +69 -0
  107. package/dist/one-way-anova.js.map +1 -0
  108. package/dist/outliers.d.ts +20 -0
  109. package/dist/outliers.d.ts.map +1 -0
  110. package/dist/outliers.js +49 -0
  111. package/dist/outliers.js.map +1 -0
  112. package/dist/poisson-distribution.d.ts +15 -0
  113. package/dist/poisson-distribution.d.ts.map +1 -0
  114. package/dist/poisson-distribution.js +44 -0
  115. package/dist/poisson-distribution.js.map +1 -0
  116. package/dist/quantile.d.ts +9 -0
  117. package/dist/quantile.d.ts.map +1 -0
  118. package/dist/quantile.js +23 -0
  119. package/dist/quantile.js.map +1 -0
  120. package/dist/random-effects.d.ts +45 -0
  121. package/dist/random-effects.d.ts.map +1 -0
  122. package/dist/random-effects.js +97 -0
  123. package/dist/random-effects.js.map +1 -0
  124. package/dist/regression.d.ts +12 -0
  125. package/dist/regression.d.ts.map +1 -0
  126. package/dist/regression.js +35 -0
  127. package/dist/regression.js.map +1 -0
  128. package/dist/student-t-distribution.d.ts +16 -0
  129. package/dist/student-t-distribution.d.ts.map +1 -0
  130. package/dist/student-t-distribution.js +54 -0
  131. package/dist/student-t-distribution.js.map +1 -0
  132. package/dist/sum.d.ts +31 -0
  133. package/dist/sum.d.ts.map +1 -0
  134. package/dist/sum.js +30 -0
  135. package/dist/sum.js.map +1 -0
  136. package/dist/t-test.d.ts +52 -0
  137. package/dist/t-test.d.ts.map +1 -0
  138. package/dist/t-test.js +81 -0
  139. package/dist/t-test.js.map +1 -0
  140. package/dist/trend.d.ts +55 -0
  141. package/dist/trend.d.ts.map +1 -0
  142. package/dist/trend.js +98 -0
  143. package/dist/trend.js.map +1 -0
  144. package/dist/uncertainty.d.ts +25 -0
  145. package/dist/uncertainty.d.ts.map +1 -0
  146. package/dist/uncertainty.js +26 -0
  147. package/dist/uncertainty.js.map +1 -0
  148. package/dist/uniform-distribution.d.ts +11 -0
  149. package/dist/uniform-distribution.d.ts.map +1 -0
  150. package/dist/uniform-distribution.js +33 -0
  151. package/dist/uniform-distribution.js.map +1 -0
  152. package/dist/welch-t-statistic.d.ts +24 -0
  153. package/dist/welch-t-statistic.d.ts.map +1 -0
  154. package/dist/welch-t-statistic.js +33 -0
  155. package/dist/welch-t-statistic.js.map +1 -0
  156. package/package.json +66 -0
package/dist/index.js ADDED
@@ -0,0 +1,34 @@
1
+ export * from "./average.js";
2
+ export * from "./beta-distribution.js";
3
+ export * from "./binomial-distribution.js";
4
+ export * from "./chi-squared-distribution.js";
5
+ export * from "./chi-squared-test.js";
6
+ export * from "./confidence-interval.js";
7
+ export * from "./dispersion.js";
8
+ export * from "./distribution.js";
9
+ export * from "./exponential-distribution.js";
10
+ export * from "./f-distribution.js";
11
+ export * from "./gamma-distribution.js";
12
+ export * from "./geometric-distribution.js";
13
+ export * from "./hierarchical-cluster.js";
14
+ export * from "./hypergeometric-distribution.js";
15
+ export * from "./kmeans.js";
16
+ export * from "./kmedoids.js";
17
+ export * from "./log-normal-distribution.js";
18
+ export * from "./negative-binomial-distribution.js";
19
+ export * from "./normal-distribution.js";
20
+ export * from "./normal-quantile.js";
21
+ export * from "./one-way-anova.js";
22
+ export * from "./outliers.js";
23
+ export * from "./poisson-distribution.js";
24
+ export * from "./quantile.js";
25
+ export * from "./random-effects.js";
26
+ export * from "./regression.js";
27
+ export * from "./student-t-distribution.js";
28
+ export * from "./sum.js";
29
+ export * from "./t-test.js";
30
+ export * from "./trend.js";
31
+ export * from "./uncertainty.js";
32
+ export * from "./uniform-distribution.js";
33
+ export * from "./welch-t-statistic.js";
34
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAC7B,cAAc,wBAAwB,CAAC;AACvC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,uBAAuB,CAAC;AACtC,cAAc,0BAA0B,CAAC;AACzC,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,qBAAqB,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,kCAAkC,CAAC;AACjD,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC;AAC9B,cAAc,8BAA8B,CAAC;AAC7C,cAAc,qCAAqC,CAAC;AACpD,cAAc,0BAA0B,CAAC;AACzC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,eAAe,CAAC;AAC9B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC;AACpC,cAAc,iBAAiB,CAAC;AAChC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,wBAAwB,CAAC"}
@@ -0,0 +1,87 @@
1
+ import type { RandomFn } from "@ac-kit/core";
2
+ /**
3
+ * Operations that define a k-means (or k-medoids) problem over an arbitrary
4
+ * value type T.
5
+ *
6
+ * By swapping `computeCentroid`, the same generic engine covers: - Standard
7
+ * k-means (arithmetic mean centroid in Euclidean space) - Circular k-means
8
+ * (circular mean centroid for angular data such as hue) - K-medoids via
9
+ * `kmedoids` (medoid update handled internally — do not pass `computeCentroid`
10
+ * there)
11
+ */
12
+ export type KmeansOps<T> = {
13
+ /** Returns the value of data point at index i. Used for kmeans++ seeding. */
14
+ readonly pointValue: (i: number) => T;
15
+ /**
16
+ * Squared distance from data point i to centroid c. Used in the assignment
17
+ * step and kmeans++ seeding. The squared form avoids a `Math.sqrt` in the hot
18
+ * assignment loop while still producing the same nearest-centroid
19
+ * assignment.
20
+ */
21
+ readonly squaredDistance: (pointIndex: number, centroid: T) => number;
22
+ /**
23
+ * Optional importance weight for data point i. Used only in k-means++
24
+ * seeding: the sampling probability is proportional to `pointWeight(i) ×
25
+ * d²(i, nearestCentroid)`, so high-weight points attract seeds more strongly
26
+ * than low-weight points at equal distance. Does NOT affect cluster
27
+ * assignment — that remains nearest-centroid by distance. Default: uniform
28
+ * weight 1.
29
+ */
30
+ readonly pointWeight?: (i: number) => number;
31
+ /**
32
+ * Distance between two centroid values. Used for the convergence check and in
33
+ * k-medoids update.
34
+ */
35
+ readonly centroidDistance: (a: T, b: T) => number;
36
+ /**
37
+ * Computes a new centroid from the given set of assigned point indices. For
38
+ * k-means: arithmetic mean (or circular mean for angular data). Do not
39
+ * provide this when calling `kmedoids` — it is supplied internally.
40
+ */
41
+ readonly computeCentroid: (pointIndices: number[]) => T;
42
+ /**
43
+ * Returns an independent copy of a centroid value to detect movement across
44
+ * iterations.
45
+ */
46
+ readonly clone: (centroid: T) => T;
47
+ };
48
+ export type KmeansOptions = {
49
+ /** Maximum number of assignment–update iterations before stopping. Default 200. */
50
+ maxIterations?: number;
51
+ /**
52
+ * Stop when the largest centroid movement in an iteration is below this
53
+ * value. Default 0.0001.
54
+ */
55
+ convergenceThreshold?: number;
56
+ /** Optional PRNG for deterministic seeding. Default: `Math.random`. */
57
+ randFn?: RandomFn | null;
58
+ };
59
+ export type KmeansCluster<T> = {
60
+ /** Final centroid (or medoid) of this cluster. */
61
+ readonly centroid: T;
62
+ /** Indices of the data points assigned to this cluster. */
63
+ readonly indices: readonly number[];
64
+ };
65
+ /**
66
+ * Generic k-means clustering.
67
+ *
68
+ * Partitions n data points into at most k clusters by iterating: 1. Assignment
69
+ * — each point is assigned to its nearest centroid. 2. Update — each centroid
70
+ * is recomputed from its assigned points via `ops.computeCentroid`.
71
+ *
72
+ * Initial centroids are chosen via k-means++ (D² weighting), which spreads
73
+ * seeds across the data distribution and reduces the risk of degenerate local
74
+ * minima.
75
+ *
76
+ * By supplying a circular-mean implementation of `computeCentroid`, this
77
+ * function also serves as circular k-means for angular data (e.g. OKLch hue).
78
+ *
79
+ * @param n Number of data points (indexed 0 … n-1).
80
+ * @param k Desired number of clusters; clamped to `min(k, n)`.
81
+ * @param ops Problem-specific operations.
82
+ * @param options Optional algorithm tuning.
83
+ * @returns One entry per non-empty cluster, with its final centroid and
84
+ * assigned indices.
85
+ */
86
+ export declare function kmeans<T>(n: number, k: number, ops: KmeansOps<T>, options?: KmeansOptions): KmeansCluster<T>[];
87
+ //# sourceMappingURL=kmeans.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kmeans.d.ts","sourceRoot":"","sources":["../src/kmeans.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAE7C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AC,EAAE,aAAa,GACrB,aAAa,CAAC,CAAC,CAAC,EAAE,CAgEpB"}
package/dist/kmeans.js ADDED
@@ -0,0 +1,126 @@
1
+ const DEFAULT_OPTIONS_ = {
2
+ maxIterations: 200,
3
+ convergenceThreshold: 0.0001,
4
+ randFn: null,
5
+ };
6
+ /**
7
+ * Generic k-means clustering.
8
+ *
9
+ * Partitions n data points into at most k clusters by iterating: 1. Assignment
10
+ * — each point is assigned to its nearest centroid. 2. Update — each centroid
11
+ * is recomputed from its assigned points via `ops.computeCentroid`.
12
+ *
13
+ * Initial centroids are chosen via k-means++ (D² weighting), which spreads
14
+ * seeds across the data distribution and reduces the risk of degenerate local
15
+ * minima.
16
+ *
17
+ * By supplying a circular-mean implementation of `computeCentroid`, this
18
+ * function also serves as circular k-means for angular data (e.g. OKLch hue).
19
+ *
20
+ * @param n Number of data points (indexed 0 … n-1).
21
+ * @param k Desired number of clusters; clamped to `min(k, n)`.
22
+ * @param ops Problem-specific operations.
23
+ * @param options Optional algorithm tuning.
24
+ * @returns One entry per non-empty cluster, with its final centroid and
25
+ * assigned indices.
26
+ */
27
+ export function kmeans(n, k, ops, options) {
28
+ if (n === 0)
29
+ return [];
30
+ const opts = {
31
+ maxIterations: options?.maxIterations ?? DEFAULT_OPTIONS_.maxIterations,
32
+ convergenceThreshold: options?.convergenceThreshold ?? DEFAULT_OPTIONS_.convergenceThreshold,
33
+ randFn: options?.randFn ?? DEFAULT_OPTIONS_.randFn,
34
+ };
35
+ const rand = opts.randFn ?? Math.random.bind(Math);
36
+ const actualK = Math.min(k, n);
37
+ const centroids = kmeansppInit_(n, actualK, ops, rand);
38
+ for (let iter = 0; iter < opts.maxIterations; iter++) {
39
+ const assignments = Array.from({ length: actualK }, () => []);
40
+ // Assignment step: each point goes to the nearest centroid.
41
+ for (let i = 0; i < n; i++) {
42
+ let minSq = Infinity;
43
+ let nearest = 0;
44
+ for (let c = 0; c < actualK; c++) {
45
+ const sq = ops.squaredDistance(i, centroids[c]);
46
+ if (sq < minSq) {
47
+ minSq = sq;
48
+ nearest = c;
49
+ }
50
+ }
51
+ assignments[nearest].push(i);
52
+ }
53
+ // Update step: recompute each centroid; track maximum movement for convergence.
54
+ let maxMove = 0;
55
+ for (let c = 0; c < actualK; c++) {
56
+ const group = assignments[c];
57
+ if (group.length === 0)
58
+ continue; // keep centroid in place
59
+ const prev = ops.clone(centroids[c]);
60
+ centroids[c] = ops.computeCentroid(group);
61
+ const move = ops.centroidDistance(centroids[c], prev);
62
+ if (move > maxMove)
63
+ maxMove = move;
64
+ }
65
+ if (maxMove < opts.convergenceThreshold)
66
+ break;
67
+ }
68
+ // Final assignment pass to get definitive cluster membership after convergence.
69
+ const finalGroups = Array.from({ length: actualK }, () => []);
70
+ for (let i = 0; i < n; i++) {
71
+ let minSq = Infinity;
72
+ let nearest = 0;
73
+ for (let c = 0; c < actualK; c++) {
74
+ const sq = ops.squaredDistance(i, centroids[c]);
75
+ if (sq < minSq) {
76
+ minSq = sq;
77
+ nearest = c;
78
+ }
79
+ }
80
+ finalGroups[nearest].push(i);
81
+ }
82
+ return finalGroups
83
+ .map((indices, c) => ({ centroid: centroids[c], indices }))
84
+ .filter((cluster) => cluster.indices.length > 0);
85
+ }
86
+ function kmeansppInit_(n, k, ops, rand) {
87
+ const centroids = [ops.clone(ops.pointValue(Math.floor(rand() * n)))];
88
+ while (centroids.length < k) {
89
+ // D²-weighted sampling: probability of picking point i is proportional to its squared
90
+ // distance to the nearest already-chosen centroid.
91
+ let total = 0;
92
+ const distances = [];
93
+ for (let i = 0; i < n; i++) {
94
+ let minSq = Infinity;
95
+ for (const c of centroids) {
96
+ const sq = ops.squaredDistance(i, c);
97
+ if (sq < minSq)
98
+ minSq = sq;
99
+ }
100
+ const weighted = minSq * (ops.pointWeight?.(i) ?? 1);
101
+ distances.push(weighted);
102
+ total += weighted;
103
+ }
104
+ if (total === 0) {
105
+ // All remaining points coincide with existing centroids — pick any point.
106
+ centroids.push(ops.clone(ops.pointValue(Math.floor(rand() * n))));
107
+ continue;
108
+ }
109
+ let remaining = rand() * total;
110
+ let pushed = false;
111
+ for (let i = 0; i < n; i++) {
112
+ remaining -= distances[i];
113
+ if (remaining <= 0) {
114
+ centroids.push(ops.clone(ops.pointValue(i)));
115
+ pushed = true;
116
+ break;
117
+ }
118
+ }
119
+ if (!pushed) {
120
+ // Floating-point residual: fall back to the last point.
121
+ centroids.push(ops.clone(ops.pointValue(n - 1)));
122
+ }
123
+ }
124
+ return centroids;
125
+ }
126
+ //# sourceMappingURL=kmeans.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kmeans.js","sourceRoot":"","sources":["../src/kmeans.ts"],"names":[],"mappings":"AAoEA,MAAM,gBAAgB,GAA4B;IACjD,aAAa,EAAE,GAAG;IAClB,oBAAoB,EAAE,MAAM;IAC5B,MAAM,EAAE,IAAI;CACZ,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,MAAM,CACrB,CAAS,EACT,CAAS,EACT,GAAiB,EACjB,OAAuB;IAEvB,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAEvB,MAAM,IAAI,GAA4B;QACrC,aAAa,EAAE,OAAO,EAAE,aAAa,IAAI,gBAAgB,CAAC,aAAa;QACvE,oBAAoB,EACnB,OAAO,EAAE,oBAAoB,IAAI,gBAAgB,CAAC,oBAAoB;QACvE,MAAM,EAAE,OAAO,EAAE,MAAM,IAAI,gBAAgB,CAAC,MAAM;KAClD,CAAC;IACF,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnD,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAE/B,MAAM,SAAS,GAAG,aAAa,CAAC,CAAC,EAAE,OAAO,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IAEvD,KAAK,IAAI,IAAI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G,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;YAC5B,SAAS,IAAI,SAAS,CAAC,CAAC,CAAE,CAAC;YAC3B,IAAI,SAAS,IAAI,CAAC,EAAE,CAAC;gBACpB,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC7C,MAAM,GAAG,IAAI,CAAC;gBACd,MAAM;YACP,CAAC;QACF,CAAC;QACD,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,wDAAwD;YACxD,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAClD,CAAC;IACF,CAAC;IAED,OAAO,SAAS,CAAC;AAClB,CAAC"}
@@ -0,0 +1,27 @@
1
+ import { KmeansCluster, KmeansOps, KmeansOptions } from "./kmeans.js";
2
+ /**
3
+ * Input operations for k-medoids: all of {@link KmeansOps} except
4
+ * `computeCentroid`.
5
+ */
6
+ export type KmedoidsOps<T> = Omit<KmeansOps<T>, "computeCentroid">;
7
+ /**
8
+ * K-medoids clustering.
9
+ *
10
+ * Like k-means, but the cluster representative is always an actual data point
11
+ * (the medoid): the point that minimises the sum of `centroidDistance` to all
12
+ * other cluster members. This guarantees the representative is a real observed
13
+ * value, not a computed average — useful when the mean is not meaningful (e.g.
14
+ * discrete labels, non-Euclidean spaces).
15
+ *
16
+ * Uses the same k-means++ seeding and assignment loop as {@link kmeans}.
17
+ *
18
+ * @param n Number of data points (indexed 0 … n-1).
19
+ * @param k Desired number of clusters; clamped to `min(k, n)`.
20
+ * @param ops Problem-specific operations. `computeCentroid` is handled
21
+ * internally.
22
+ * @param options Optional algorithm tuning.
23
+ * @returns One entry per non-empty cluster, with its medoid and assigned
24
+ * indices.
25
+ */
26
+ export declare function kmedoids<T>(n: number, k: number, ops: KmedoidsOps<T>, options?: KmeansOptions): KmeansCluster<T>[];
27
+ //# sourceMappingURL=kmedoids.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kmedoids.d.ts","sourceRoot":"","sources":["../src/kmedoids.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,aAAa,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE9E;;;GAGG;AACH,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,iBAAiB,CAAC,CAAC;AAEnE;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EACzB,CAAC,EAAE,MAAM,EACT,CAAC,EAAE,MAAM,EACT,GAAG,EAAE,WAAW,CAAC,CAAC,CAAC,EACnB,OAAO,CAAC,EAAE,aAAa,GACrB,aAAa,CAAC,CAAC,CAAC,EAAE,CAEpB"}
@@ -0,0 +1,47 @@
1
+ import { kmeans } from "./kmeans.js";
2
+ /**
3
+ * K-medoids clustering.
4
+ *
5
+ * Like k-means, but the cluster representative is always an actual data point
6
+ * (the medoid): the point that minimises the sum of `centroidDistance` to all
7
+ * other cluster members. This guarantees the representative is a real observed
8
+ * value, not a computed average — useful when the mean is not meaningful (e.g.
9
+ * discrete labels, non-Euclidean spaces).
10
+ *
11
+ * Uses the same k-means++ seeding and assignment loop as {@link kmeans}.
12
+ *
13
+ * @param n Number of data points (indexed 0 … n-1).
14
+ * @param k Desired number of clusters; clamped to `min(k, n)`.
15
+ * @param ops Problem-specific operations. `computeCentroid` is handled
16
+ * internally.
17
+ * @param options Optional algorithm tuning.
18
+ * @returns One entry per non-empty cluster, with its medoid and assigned
19
+ * indices.
20
+ */
21
+ export function kmedoids(n, k, ops, options) {
22
+ return kmeans(n, k, { ...ops, computeCentroid: medoidFn_(ops) }, options);
23
+ }
24
+ /**
25
+ * Returns a `computeCentroid` function that selects the medoid: the point in
26
+ * the cluster with the smallest total `centroidDistance` to all other members.
27
+ */
28
+ function medoidFn_(ops) {
29
+ return (indices) => {
30
+ let minTotal = Infinity;
31
+ let bestIdx = indices[0];
32
+ for (const i of indices) {
33
+ const vi = ops.pointValue(i);
34
+ let total = 0;
35
+ for (const j of indices) {
36
+ if (j !== i)
37
+ total += ops.centroidDistance(vi, ops.pointValue(j));
38
+ }
39
+ if (total < minTotal) {
40
+ minTotal = total;
41
+ bestIdx = i;
42
+ }
43
+ }
44
+ return ops.clone(ops.pointValue(bestIdx));
45
+ };
46
+ }
47
+ //# sourceMappingURL=kmedoids.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kmedoids.js","sourceRoot":"","sources":["../src/kmedoids.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAA2C,MAAM,aAAa,CAAC;AAQ9E;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,QAAQ,CACvB,CAAS,EACT,CAAS,EACT,GAAmB,EACnB,OAAuB;IAEvB,OAAO,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,GAAG,GAAG,EAAE,eAAe,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;AAC3E,CAAC;AAED;;;GAGG;AACH,SAAS,SAAS,CAAI,GAAmB;IACxC,OAAO,CAAC,OAAO,EAAE,EAAE;QAClB,IAAI,QAAQ,GAAG,QAAQ,CAAC;QACxB,IAAI,OAAO,GAAG,OAAO,CAAC,CAAC,CAAE,CAAC;QAE1B,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;YACzB,MAAM,EAAE,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAC7B,IAAI,KAAK,GAAG,CAAC,CAAC;YACd,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;gBACzB,IAAI,CAAC,KAAK,CAAC;oBAAE,KAAK,IAAI,GAAG,CAAC,gBAAgB,CAAC,EAAE,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;YACnE,CAAC;YACD,IAAI,KAAK,GAAG,QAAQ,EAAE,CAAC;gBACtB,QAAQ,GAAG,KAAK,CAAC;gBACjB,OAAO,GAAG,CAAC,CAAC;YACb,CAAC;QACF,CAAC;QAED,OAAO,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;IAC3C,CAAC,CAAC;AACH,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { Distribution } from "./distribution.js";
2
+ /**
3
+ * The log-normal distribution: a variable whose logarithm is normal.
4
+ *
5
+ * The parameters name the log scale rather than the variable's own, because
6
+ * that is what they describe — `logMean` is not the distribution's mean, which
7
+ * is `exp(logMean + logStandardDeviation² / 2)` and is exposed separately.
8
+ *
9
+ * @param logMean Mean of the underlying normal.
10
+ * @param logStandardDeviation Standard deviation of it; must be positive.
11
+ * @returns The distribution.
12
+ * @throws {RangeError} When `logStandardDeviation` is not positive.
13
+ */
14
+ export declare function logNormalDistribution(logMean?: number, logStandardDeviation?: number): Distribution;
15
+ //# sourceMappingURL=log-normal-distribution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-normal-distribution.d.ts","sourceRoot":"","sources":["../src/log-normal-distribution.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGtD;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CACpC,OAAO,SAAI,EACX,oBAAoB,SAAI,GACtB,YAAY,CAmCd"}
@@ -0,0 +1,44 @@
1
+ import { SQRT_TWO_PI } from "@ac-kit/math-scalar";
2
+ import { assertProbability_ } from "./_assert-probability.js";
3
+ import { inverseTransformSample_ } from "./_inverse-transform-sample.js";
4
+ import { normalDistribution } from "./normal-distribution.js";
5
+ /**
6
+ * The log-normal distribution: a variable whose logarithm is normal.
7
+ *
8
+ * The parameters name the log scale rather than the variable's own, because
9
+ * that is what they describe — `logMean` is not the distribution's mean, which
10
+ * is `exp(logMean + logStandardDeviation² / 2)` and is exposed separately.
11
+ *
12
+ * @param logMean Mean of the underlying normal.
13
+ * @param logStandardDeviation Standard deviation of it; must be positive.
14
+ * @returns The distribution.
15
+ * @throws {RangeError} When `logStandardDeviation` is not positive.
16
+ */
17
+ export function logNormalDistribution(logMean = 0, logStandardDeviation = 1) {
18
+ if (!(logStandardDeviation > 0)) {
19
+ throw new RangeError(`logNormalDistribution: logStandardDeviation must be positive, got ${logStandardDeviation}`);
20
+ }
21
+ const underlying = normalDistribution(logMean, logStandardDeviation);
22
+ const quantile = (probability) => {
23
+ assertProbability_("logNormalDistribution", probability);
24
+ return Math.exp(underlying.quantile(probability));
25
+ };
26
+ const variance = Math.expm1(logStandardDeviation * logStandardDeviation) *
27
+ Math.exp(2 * logMean + logStandardDeviation * logStandardDeviation);
28
+ return {
29
+ density: (x) => {
30
+ if (x <= 0) {
31
+ return 0;
32
+ }
33
+ const z = (Math.log(x) - logMean) / logStandardDeviation;
34
+ return Math.exp(-0.5 * z * z) / (x * logStandardDeviation * SQRT_TWO_PI);
35
+ },
36
+ cdf: (x) => (x <= 0 ? 0 : underlying.cdf(Math.log(x))),
37
+ survival: (x) => (x <= 0 ? 1 : underlying.survival(Math.log(x))),
38
+ quantile,
39
+ sample: (random) => inverseTransformSample_(quantile, random),
40
+ mean: Math.exp(logMean + (logStandardDeviation * logStandardDeviation) / 2),
41
+ variance,
42
+ };
43
+ }
44
+ //# sourceMappingURL=log-normal-distribution.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-normal-distribution.js","sourceRoot":"","sources":["../src/log-normal-distribution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAElD,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAEzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CA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AAC,CAAC,CAAC,CAAC;QACtD,QAAQ,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAChE,QAAQ;QACR,MAAM,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,uBAAuB,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC7D,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,OAAO,GAAG,CAAC,oBAAoB,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAC;QAC3E,QAAQ;KACR,CAAC;AACH,CAAC"}
@@ -0,0 +1,18 @@
1
+ import type { Distribution } from "./distribution.js";
2
+ /**
3
+ * The negative binomial distribution — the number of **failures** before the
4
+ * `successes`-th success.
5
+ *
6
+ * Counting failures rather than trials, so that
7
+ * `negativeBinomialDistribution(1, p)` is exactly `geometricDistribution(p)`.
8
+ * `successes` need not be an integer; the Pólya form with a real stopping
9
+ * parameter is the same formula.
10
+ *
11
+ * @param successes Number of successes to wait for; must be positive.
12
+ * @param probability Success probability of one attempt, in `(0, 1]`.
13
+ * @returns The distribution.
14
+ * @throws {RangeError} When `successes` is not positive, or `probability` is
15
+ * outside `(0, 1]`.
16
+ */
17
+ export declare function negativeBinomialDistribution(successes: number, probability: number): Distribution;
18
+ //# sourceMappingURL=negative-binomial-distribution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"negative-binomial-distribution.d.ts","sourceRoot":"","sources":["../src/negative-binomial-distribution.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEtD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,4BAA4B,CAC3C,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,MAAM,GACjB,YAAY,CAwDd"}
@@ -0,0 +1,64 @@
1
+ import { logGamma, regularizedIncompleteBeta } from "@ac-kit/math-analysis";
2
+ import { assertProbability_ } from "./_assert-probability.js";
3
+ import { discreteQuantile_ } from "./_discrete-quantile.js";
4
+ import { inverseTransformSample_ } from "./_inverse-transform-sample.js";
5
+ /**
6
+ * The negative binomial distribution — the number of **failures** before the
7
+ * `successes`-th success.
8
+ *
9
+ * Counting failures rather than trials, so that
10
+ * `negativeBinomialDistribution(1, p)` is exactly `geometricDistribution(p)`.
11
+ * `successes` need not be an integer; the Pólya form with a real stopping
12
+ * parameter is the same formula.
13
+ *
14
+ * @param successes Number of successes to wait for; must be positive.
15
+ * @param probability Success probability of one attempt, in `(0, 1]`.
16
+ * @returns The distribution.
17
+ * @throws {RangeError} When `successes` is not positive, or `probability` is
18
+ * outside `(0, 1]`.
19
+ */
20
+ export function negativeBinomialDistribution(successes, probability) {
21
+ if (!(successes > 0)) {
22
+ throw new RangeError(`negativeBinomialDistribution: successes must be positive, got ${successes}`);
23
+ }
24
+ if (!(probability > 0 && probability <= 1)) {
25
+ throw new RangeError(`negativeBinomialDistribution: probability must be in (0, 1], got ${probability}`);
26
+ }
27
+ const cdf = (x) => {
28
+ const failures = Math.floor(x);
29
+ return failures < 0
30
+ ? 0
31
+ : regularizedIncompleteBeta(successes, failures + 1, probability);
32
+ };
33
+ const quantile = (target) => {
34
+ assertProbability_("negativeBinomialDistribution", target);
35
+ return discreteQuantile_(cdf, target, 0, Number.POSITIVE_INFINITY);
36
+ };
37
+ return {
38
+ density: (x) => {
39
+ if (!Number.isInteger(x) || x < 0) {
40
+ return 0;
41
+ }
42
+ if (probability === 1) {
43
+ return x === 0 ? 1 : 0;
44
+ }
45
+ return Math.exp(logGamma(x + successes) -
46
+ logGamma(x + 1) -
47
+ logGamma(successes) +
48
+ successes * Math.log(probability) +
49
+ x * Math.log1p(-probability));
50
+ },
51
+ cdf,
52
+ survival: (x) => {
53
+ const failures = Math.floor(x);
54
+ return failures < 0
55
+ ? 1
56
+ : regularizedIncompleteBeta(failures + 1, successes, 1 - probability);
57
+ },
58
+ quantile,
59
+ sample: (random) => inverseTransformSample_(quantile, random),
60
+ mean: (successes * (1 - probability)) / probability,
61
+ variance: (successes * (1 - probability)) / (probability * probability),
62
+ };
63
+ }
64
+ //# sourceMappingURL=negative-binomial-distribution.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"negative-binomial-distribution.js","sourceRoot":"","sources":["../src/negative-binomial-distribution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAE5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAGzE;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,4BAA4B,CAC3C,SAAiB,EACjB,WAAmB;IAEnB,IAAI,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,CAAC;QACtB,MAAM,IAAI,UAAU,CACnB,iEAAiE,SAAS,EAAE,CAC5E,CAAC;IACH,CAAC;IACD,IAAI,CAAC,CAAC,WAAW,GAAG,CAAC,IAAI,WAAW,IAAI,CAAC,CAAC,EAAE,CAAC;QAC5C,MAAM,IAAI,UAAU,CACnB,oEAAoE,WAAW,EAAE,CACjF,CAAC;IACH,CAAC;IAED,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,EAAE;QACzB,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAE/B,OAAO,QAAQ,GAAG,CAAC;YAClB,CAAC,CAAC,CAAC;YACH,CAAC,CAAC,yBAAyB,CAAC,SAAS,EAAE,QAAQ,GAAG,CAAC,EAAE,WAAW,CAAC,CAAC;IACpE,CAAC,CAAC;IAEF,MAAM,QAAQ,GAAG,CAAC,MAAc,EAAE,EAAE;QACnC,kBAAkB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ACnD,QAAQ,EAAE,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC,CAAC,GAAG,CAAC,WAAW,GAAG,WAAW,CAAC;KACvE,CAAC;AACH,CAAC"}
@@ -0,0 +1,16 @@
1
+ import type { Distribution } from "./distribution.js";
2
+ /**
3
+ * The normal (Gaussian) distribution.
4
+ *
5
+ * Both tails go through `erfc` rather than through one another: `cdf` uses the
6
+ * reflected argument so the lower tail stays exact, and `survival` the direct
7
+ * one. Computing either as `1 −` the other loses the whole answer beyond about
8
+ * four standard deviations, which is where a p-value lives.
9
+ *
10
+ * @param mean Centre of the distribution.
11
+ * @param standardDeviation Spread; must be positive.
12
+ * @returns The distribution.
13
+ * @throws {RangeError} When `standardDeviation` is not positive.
14
+ */
15
+ export declare function normalDistribution(mean?: number, standardDeviation?: number): Distribution;
16
+ //# sourceMappingURL=normal-distribution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normal-distribution.d.ts","sourceRoot":"","sources":["../src/normal-distribution.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGtD;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,CACjC,IAAI,SAAI,EACR,iBAAiB,SAAI,GACnB,YAAY,CA4Bd"}
@@ -0,0 +1,41 @@
1
+ import { erfc } from "@ac-kit/math-analysis";
2
+ import { SQRT1_2, SQRT_TWO_PI } from "@ac-kit/math-scalar";
3
+ import { assertProbability_ } from "./_assert-probability.js";
4
+ import { inverseTransformSample_ } from "./_inverse-transform-sample.js";
5
+ import { normalQuantile } from "./normal-quantile.js";
6
+ /**
7
+ * The normal (Gaussian) distribution.
8
+ *
9
+ * Both tails go through `erfc` rather than through one another: `cdf` uses the
10
+ * reflected argument so the lower tail stays exact, and `survival` the direct
11
+ * one. Computing either as `1 −` the other loses the whole answer beyond about
12
+ * four standard deviations, which is where a p-value lives.
13
+ *
14
+ * @param mean Centre of the distribution.
15
+ * @param standardDeviation Spread; must be positive.
16
+ * @returns The distribution.
17
+ * @throws {RangeError} When `standardDeviation` is not positive.
18
+ */
19
+ export function normalDistribution(mean = 0, standardDeviation = 1) {
20
+ if (!(standardDeviation > 0)) {
21
+ throw new RangeError(`normalDistribution: standardDeviation must be positive, got ${standardDeviation}`);
22
+ }
23
+ const standardise = (x) => (x - mean) / standardDeviation;
24
+ const quantile = (probability) => {
25
+ assertProbability_("normalDistribution", probability);
26
+ return mean + standardDeviation * normalQuantile(probability);
27
+ };
28
+ return {
29
+ density: (x) => {
30
+ const z = standardise(x);
31
+ return Math.exp(-0.5 * z * z) / (standardDeviation * SQRT_TWO_PI);
32
+ },
33
+ cdf: (x) => 0.5 * erfc(-standardise(x) * SQRT1_2),
34
+ survival: (x) => 0.5 * erfc(standardise(x) * SQRT1_2),
35
+ quantile,
36
+ sample: (random) => inverseTransformSample_(quantile, random),
37
+ mean,
38
+ variance: standardDeviation * standardDeviation,
39
+ };
40
+ }
41
+ //# sourceMappingURL=normal-distribution.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normal-distribution.js","sourceRoot":"","sources":["../src/normal-distribution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAE3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAEzE,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,kBAAkB,CACjC,IAAI,GAAG,CAAC,EACR,iBAAiB,GAAG,CAAC;IAErB,IAAI,CAAC,CAAC,iBAAiB,GAAG,CAAC,CAAC,EAAE,CAAC;QAC9B,MAAM,IAAI,UAAU,CACnB,+DAA+D,iBAAiB,EAAE,CAClF,CAAC;IACH,CAAC;IAED,MAAM,WAAW,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,iBAAiB,CAAC;IAElE,MAAM,QAAQ,GAAG,CAAC,WAAmB,EAAE,EAAE;QACxC,kBAAkB,CAAC,oBAAoB,EAAE,WAAW,CAAC,CAAC;QAEtD,OAAO,IAAI,GAAG,iBAAiB,GAAG,cAAc,CAAC,WAAW,CAAC,CAAC;IAC/D,CAAC,CAAC;IAEF,OAAO;QACN,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE;YACd,MAAM,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;YAEzB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,iBAAiB,GAAG,WAAW,CAAC,CAAC;QACnE,CAAC;QACD,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC;QACjD,QAAQ,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC;QACrD,QAAQ;QACR,MAAM,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,uBAAuB,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC7D,IAAI;QACJ,QAAQ,EAAE,iBAAiB,GAAG,iBAAiB;KAC/C,CAAC;AACH,CAAC"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Inverse of the standard normal cumulative distribution function (the probit
3
+ * function): the value `x` such that a standard normal variable falls at or
4
+ * below `x` with probability `probability`.
5
+ *
6
+ * Acklam's rational approximation, whose relative error is bounded by 1.15e-9,
7
+ * refined by a single Halley step against `erfc`. That step triples the correct
8
+ * digits, so the result is accurate to the last few bits rather than to nine
9
+ * decimals — which matters because the error is _relative_, and the absolute
10
+ * error of the bare approximation grows with the quantile, reaching about 7e-9
11
+ * out at `p = 1e-12`.
12
+ *
13
+ * @param probability Probability in `[0, 1]`.
14
+ * @returns The quantile; `-Infinity` for `0`, `Infinity` for `1`, `NaN` for
15
+ * `NaN`.
16
+ * @throws {RangeError} When `probability` is outside `[0, 1]`.
17
+ */
18
+ export declare function normalQuantile(probability: number): number;
19
+ //# sourceMappingURL=normal-quantile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normal-quantile.d.ts","sourceRoot":"","sources":["../src/normal-quantile.ts"],"names":[],"mappings":"AA+BA;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAiB1D"}