wilson-interval 5.0.0 → 5.1.1

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.
@@ -0,0 +1,11 @@
1
+ # To get started with Dependabot version updates, you'll need to specify which
2
+ # package ecosystems to update and where the package manifests are located.
3
+ # Please see the documentation for all configuration options:
4
+ # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
5
+
6
+ version: 2
7
+ updates:
8
+ - package-ecosystem: "npm" # See documentation for possible values
9
+ directory: "/" # Location of package manifests
10
+ schedule:
11
+ interval: "weekly"
@@ -1,5 +1,7 @@
1
- # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
2
- # For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
1
+ # Runs the tests, then publishes the package to npm when a GitHub release is created.
2
+ # Authenticates with npm trusted publishing (OIDC), so no npm token secret is needed,
3
+ # and npm adds a provenance attestation automatically.
4
+ # See https://docs.npmjs.com/trusted-publishers
3
5
 
4
6
  name: Node.js Package
5
7
 
@@ -7,6 +9,9 @@ on:
7
9
  release:
8
10
  types: [created]
9
11
 
12
+ permissions:
13
+ contents: read
14
+
10
15
  jobs:
11
16
  build:
12
17
  runs-on: ubuntu-latest
@@ -14,20 +19,23 @@ jobs:
14
19
  - uses: actions/checkout@v4
15
20
  - uses: actions/setup-node@v4
16
21
  with:
17
- node-version: 20
22
+ node-version: 24
18
23
  - run: npm ci
19
24
  - run: npm test
20
25
 
21
26
  publish-npm:
22
27
  needs: build
23
28
  runs-on: ubuntu-latest
29
+ permissions:
30
+ contents: read
31
+ id-token: write # lets npm exchange a GitHub OIDC token for publish rights
24
32
  steps:
25
33
  - uses: actions/checkout@v4
26
34
  - uses: actions/setup-node@v4
27
35
  with:
28
- node-version: 20
36
+ node-version: 24
29
37
  registry-url: https://registry.npmjs.org/
38
+ # Trusted publishing needs npm 11.5.1 or later
39
+ - run: npm install -g npm@latest
30
40
  - run: npm ci
31
41
  - run: npm publish
32
- env:
33
- NODE_AUTH_TOKEN: ${{secrets.npm_token}}
package/README.md CHANGED
@@ -4,8 +4,6 @@
4
4
  [![npm](https://img.shields.io/npm/v/wilson-interval.svg)](https://www.npmjs.com/package/wilson-interval)
5
5
  [![npm](https://img.shields.io/npm/dt/wilson-interval.svg?colorB=32CD32)](https://www.npmjs.com/package/wilson-interval)
6
6
  [![codecov](https://codecov.io/github/erikfox/wilson-interval/graph/badge.svg?token=R0A2KJQWU6)](https://codecov.io/github/erikfox/wilson-interval)
7
-
8
-
9
7
  [![Pull Requests Welcome](https://img.shields.io/badge/pull_requests-welcome-FF69B4.svg)]()
10
8
  [![](https://img.shields.io/github/issues-raw/erikfox/wilson-interval.svg?colorB=FF69B4)](https://github.com/erikfox/wilson-interval/issues)
11
9
 
@@ -27,20 +25,15 @@ import wilson from 'wilson-interval';
27
25
 
28
26
  ## Usage
29
27
 
30
- ### wilson(observed, sample[, population ][, options ]);
28
+ ### wilson(observed, sample[, population ][, confidence ]);
31
29
 
32
- - `observed` - Number of observed positive outcomes.
33
-
34
- - `sample` - Size of sample.
30
+ - `observed` - Required, accepts `Number >= 0`. Count of observed positive outcomes as a whole number.
31
+ - `sample` - Required, accepts `Number > 0`. Size of sample as a whole number.
35
32
 
36
33
  Optional arguments:
37
34
 
38
- - `population` - Default `false`. Total population from which sample was taken (to use **[Singleton's adjustment](https://corplingstats.wordpress.com/2012/04/30/inferential-statistics/)**<sup>[1]</sup>).
39
-
40
- - `options` - Default `{}`. Options object. Available parameters:
41
-
42
- - `confidence` - Default `0.95`. Desired confidence level of interval.
43
- - `precision` - Default `20`. Number of significant figures to use in calculations and output.
35
+ - `population` - Default `null`, accepts `Number > 0`. Total population from which sample was taken (to use **[Singleton's adjustment](https://corplingstats.wordpress.com/2012/04/30/inferential-statistics/)**<sup>[1]</sup>). Must be a positive whole number.
36
+ - `confidence` - Default `0.95`, accepts `1 > Number > 0`. Desired confidence level of interval as a fractional decimal value between 0 and 1.
44
37
 
45
38
  #### Example
46
39
  ```js
@@ -49,9 +42,9 @@ return wilson(5, 100);
49
42
  returns
50
43
  ```json
51
44
  {
52
- "center": "0.066647073981204927863",
53
- "high": "0.11175046869375655694",
54
- "low": "0.021543679268653298792",
45
+ "center": 0.06664707421899263,
46
+ "high": 0.11175046929755608,
47
+ "low": 0.02154367914042918
55
48
  }
56
49
  ```
57
50
 
@@ -76,6 +69,12 @@ Uses a known, finite population size to inform the degree of uncertainty of the
76
69
  1. Your sample size represents a significant portion of the population.
77
70
  2. You have an imperfect original sample, from which you can only verify a subsample. The original sample can serve as a "population" to produce a verification interval to be combined with the first.<sup>[2]</sup>
78
71
 
72
+ **HOW IT'S CALCULATED:**
73
+
74
+ The observed proportion `p = observed / sample` is unchanged. The sample size used for the interval is divided by ν², where ν = √((N − n) / (N − 1)) is the finite population correction.<sup>[1]</sup> If `sample` equals `population`, the interval collapses to `p`.
75
+
76
+ > **Note:** The worked example in *Coping with imperfect data*<sup>[2]</sup> (5 of 100 from a population of 227, giving 0.0240–0.1011) divides n by ν instead of ν². This module follows the ν² adjustment described in [1], which matches the variance of sampling without replacement, so it returns 0.0264–0.0926 for that example.
77
+
79
78
  ## Sources
80
79
 
81
80
  <sup>[1]</sup> [Wallis, Sean 2012. *Inferential Statistics — and other animals*. London: Survey of English Usage, UCL.](https://corplingstats.wordpress.com/2012/04/30/inferential-statistics/)
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "wilson-interval",
3
- "version": "5.0.0",
3
+ "version": "5.1.1",
4
4
  "author": "Erik Fox <eriktfox@gmail.com> (http://erikfox.dev)",
5
- "description": "Used to calculate the high bound, low bound, and center of a Wilson score interval. Features support for continuity correction and Singleton's adjustment.",
5
+ "description": "Used to calculate the high bound, low bound, and center of a Wilson score interval. Features support for Singleton's adjustment (finite population correction).",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/erikfox/wilson-interval",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "https://github.com/erikfox/wilson-interval.git"
10
+ "url": "git+https://github.com/erikfox/wilson-interval.git"
11
11
  },
12
12
  "bugs": {
13
13
  "url": "https://github.com/erikfox/wilson-interval/issues"
@@ -36,9 +36,5 @@
36
36
  "scripts": {
37
37
  "test": "node --test src/index.test.js",
38
38
  "test:cc": "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info src/index.test.js"
39
- },
40
- "dependencies": {
41
- "mathjs": "^14.0.0",
42
- "pnormaldist": "^1.0.0"
43
39
  }
44
40
  }
package/src/index.js CHANGED
@@ -1,45 +1,53 @@
1
- import { create, all } from 'mathjs';
2
- import pnormaldist from 'pnormaldist';
3
-
4
- export default function wilson(observed, sample, population = false, options = {}) {
5
- const {
6
- confidence = 0.95,
7
- precision = 20,
8
- } = options;
9
-
10
- const math = create(all, { number: 'BigNumber', precision });
1
+ export default function wilson(observed, sample, population = null, confidence = 0.95) {
2
+ if (!Number.isSafeInteger(observed) || observed < 0) {
3
+ throw new Error('Observed must be a non-negative whole number');
4
+ }
11
5
 
12
- observed = math.bignumber(observed);
13
- sample = math.bignumber(sample);
6
+ if (!Number.isSafeInteger(sample) || sample <= 0) {
7
+ throw new Error('Sample must be a positive whole number');
8
+ }
14
9
 
15
- const proportion = math.evaluate('observed / sample', { observed, sample });
10
+ if (observed > sample) {
11
+ throw new Error('Observed must not exceed sample');
12
+ }
16
13
 
17
- if (population) {
18
- sample = math.evaluate('sample / (sqrt(1 - sample / population))', { sample, population });
14
+ if (typeof confidence !== 'number' || Number.isNaN(confidence) || confidence <= 0 || confidence >= 1) {
15
+ throw new Error('Confidence must be a decimal between 0 and 1');
19
16
  }
20
17
 
21
- const zScore = pnormaldist(math.evaluate('1 - (1 - confidence) / 2', { confidence }));
18
+ const p = observed / sample;
19
+ let n = sample;
22
20
 
23
- const scope = {
24
- p: math.bignumber(proportion),
25
- n: math.bignumber(sample),
26
- z: math.bignumber(zScore),
27
- };
21
+ if (population !== null) {
22
+ if (!Number.isSafeInteger(population) || population <= 0) {
23
+ throw new Error('Population must be a positive whole number');
24
+ }
25
+ if (sample > population) {
26
+ throw new Error('Sample must not exceed population');
27
+ }
28
+ // The whole population was observed, so there is no uncertainty
29
+ if (sample === population) {
30
+ return { high: p, center: p, low: p };
31
+ }
32
+ // Finite population correction: the standard deviation scales by
33
+ // ν = √((N − n) / (N − 1)), the exact hypergeometric factor, which is
34
+ // equivalent to dividing n by ν². p is unchanged.
35
+ // See Wallis (2012), "Inferential statistics — and other animals".
36
+ n = sample * (population - 1) / (population - sample);
37
+ }
28
38
 
29
- const high = math.format(math.evaluate(
30
- '(p + z * z / (2 * n) + z * sqrt(p * (1 - p) / n + z * z / (4 * (n * n)))) / (1 + z * z / n)',
31
- scope,
32
- ));
39
+ // Computed from the lower tail so confidence near 1 keeps its precision
40
+ // (1 − (1 − confidence) / 2 can round to exactly 1 and give z = Infinity)
41
+ const z = -normalQuantile((1 - confidence) / 2);
33
42
 
34
- const low = math.format(math.evaluate(
35
- '(p + z * z / (2 * n) - z * sqrt(p * (1 - p) / n + z * z / (4 * (n * n)))) / (1 + z * z / n)',
36
- scope,
37
- ));
43
+ const denominator = 1 + z * z / n;
44
+ const center = (p + z * z / (2 * n)) / denominator;
45
+ const margin = z * Math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denominator;
38
46
 
39
- const center = math.format(math.evaluate(
40
- '(p + z * z / (2 * n)) / (1 + z * z / n)',
41
- scope,
42
- ));
47
+ // The bounds are exactly 0 at p = 0 and exactly 1 at p = 1; elsewhere, clamp
48
+ // away floating-point drift so that 0 ≤ low ≤ p ≤ high ≤ 1 always holds
49
+ const low = observed === 0 ? 0 : Math.max(0, Math.min(center - margin, p));
50
+ const high = observed === sample ? 1 : Math.min(1, Math.max(center + margin, p));
43
51
 
44
52
  return {
45
53
  high,
@@ -47,3 +55,66 @@ export default function wilson(observed, sample, population = false, options = {
47
55
  low,
48
56
  };
49
57
  }
58
+
59
+ // Returns the quantile (inverse CDF) for the standard normal distribution
60
+ export function normalQuantile(p) {
61
+ if (Number.isNaN(p) || p < 0 || p > 1) {
62
+ throw new Error('p must be a decimal between 0 and 1');
63
+ }
64
+ if (p === 0) return -Infinity;
65
+ if (p === 1) return Infinity;
66
+
67
+ // Coefficients in rational approximations
68
+ const a = [
69
+ -3.969683028665376e+01,
70
+ 2.209460984245205e+02,
71
+ -2.759285104469687e+02,
72
+ 1.383577518672690e+02,
73
+ -3.066479806614716e+01,
74
+ 2.506628277459239e+00
75
+ ];
76
+ const b = [
77
+ -5.447609879822406e+01,
78
+ 1.615858368580409e+02,
79
+ -1.556989798598866e+02,
80
+ 6.680131188771972e+01,
81
+ -1.328068155288572e+01
82
+ ];
83
+ const c = [
84
+ -7.784894002430293e-03,
85
+ -3.223964580411365e-01,
86
+ -2.400758277161838e+00,
87
+ -2.549732539343734e+00,
88
+ 4.374664141464968e+00,
89
+ 2.938163982698783e+00
90
+ ];
91
+ const d = [
92
+ 7.784695709041462e-03,
93
+ 3.224671290700398e-01,
94
+ 2.445134137142996e+00,
95
+ 3.754408661907416e+00
96
+ ];
97
+
98
+ // Define break-points
99
+ const plow = 0.02425;
100
+ const phigh = 1 - plow;
101
+
102
+ let q, r;
103
+ if (p < plow) {
104
+ // Rational approximation for lower region
105
+ q = Math.sqrt(-2 * Math.log(p));
106
+ return (((((c[0]*q + c[1])*q + c[2])*q + c[3])*q + c[4])*q + c[5]) /
107
+ ((((d[0]*q + d[1])*q + d[2])*q + d[3])*q + 1);
108
+ } else if (phigh < p) {
109
+ // Rational approximation for upper region
110
+ q = Math.sqrt(-2 * Math.log(1 - p));
111
+ return -(((((c[0]*q + c[1])*q + c[2])*q + c[3])*q + c[4])*q + c[5]) /
112
+ ((((d[0]*q + d[1])*q + d[2])*q + d[3])*q + 1);
113
+ } else {
114
+ // Rational approximation for central region
115
+ q = p - 0.5;
116
+ r = q * q;
117
+ return (((((a[0]*r + a[1])*r + a[2])*r + a[3])*r + a[4])*r + a[5])*q /
118
+ (((((b[0]*r + b[1])*r + b[2])*r + b[3])*r + b[4])*r + 1);
119
+ }
120
+ }
package/src/index.test.js CHANGED
@@ -1,54 +1,203 @@
1
- import wilson from './index.js';
1
+ import wilson, { normalQuantile } from './index.js';
2
2
  import test from 'node:test';
3
3
  import assert from 'node:assert';
4
4
  import { describe } from 'node:test';
5
5
 
6
+ // normalQuantile() has ~1e-9 relative error, so compare with a tolerance
7
+ function assertInterval(actual, expected, tolerance = 1e-9) {
8
+ for (const key of ['low', 'center', 'high']) {
9
+ assert.ok(
10
+ Math.abs(actual[key] - expected[key]) < tolerance,
11
+ `${key}: expected ${expected[key]}, got ${actual[key]}`
12
+ );
13
+ }
14
+ assert.ok(actual.low <= actual.center && actual.center <= actual.high, 'low <= center <= high');
15
+ }
16
+
17
+ function assertBounds({ low, center, high }, p) {
18
+ assert.ok(0 <= low, `low ${low} < 0`);
19
+ assert.ok(low <= p && p <= high, `p ${p} not within [${low}, ${high}]`);
20
+ assert.ok(low <= center && center <= high, `center ${center} not within [${low}, ${high}]`);
21
+ assert.ok(high <= 1, `high ${high} > 1`);
22
+ }
23
+
24
+ describe('wilson() bounds', () => {
25
+ test('observed = 0 gives low exactly 0', () => {
26
+ assert.strictEqual(wilson(0, 1e6, 1000001).low, 0);
27
+ assert.strictEqual(wilson(0, 1, 10, 0.99).low, 0);
28
+ });
29
+
30
+ test('observed = sample gives high exactly 1', () => {
31
+ assert.strictEqual(wilson(100, 100, 101).high, 1);
32
+ assert.strictEqual(wilson(1e6, 1e6).high, 1);
33
+ assert.strictEqual(wilson(1, 1, null, 0.99).high, 1);
34
+ });
35
+
36
+ test('0 <= low <= p <= high <= 1 across a grid of inputs', () => {
37
+ const confidences = [0.5, 0.8, 0.9, 0.95, 0.99, 0.999];
38
+ for (let sample = 1; sample <= 120; sample++) {
39
+ for (const population of [null, sample, sample + 1, sample * 2, sample * 50]) {
40
+ for (const confidence of confidences) {
41
+ for (let observed = 0; observed <= sample; observed++) {
42
+ assertBounds(wilson(observed, sample, population, confidence), observed / sample);
43
+ }
44
+ }
45
+ }
46
+ }
47
+ });
48
+
49
+ test('very large sample stays within bounds', () => {
50
+ const sample = 2 ** 53 - 1;
51
+ assertBounds(wilson(sample - 1, sample), (sample - 1) / sample);
52
+ });
53
+ });
54
+
6
55
  describe('wilson()', () => {
7
- describe('handles base args', () => {
8
- test('wilson(5, 100)', () => {
56
+ describe('handles required args', () => {
57
+ test('good `observed` and `sample` input', () => {
9
58
  const result = wilson(5, 100);
10
59
 
11
60
  assert.deepEqual(result, {
12
- "high": "0.11175046869375655694",
13
- "center": "0.066647073981204927863",
14
- "low": "0.021543679268653298792",
61
+ center: 0.06664707421899263,
62
+ high: 0.11175046929755608,
63
+ low: 0.02154367914042918
15
64
  });
16
65
  });
17
- });
18
66
 
19
- describe('handles population arg', () => {
20
- test('wilson(5, 100, 227)', () => {
21
- const result = wilson(5, 100, 227);
22
-
23
- assert.deepEqual(result, {
24
- "center": "0.062568829500944323976",
25
- "high": "0.10110044321850152858",
26
- "low": "0.024037215783387119365",
67
+ test('bad `observed` = -1 input', () => {
68
+ assert.throws(() => wilson(-1, 100), {
69
+ message: 'Observed must be a non-negative whole number'
70
+ });
71
+ });
72
+
73
+ test('bad `sample` = 0 input', () => {
74
+ assert.throws(() => wilson(5, 0), {
75
+ message: 'Sample must be a positive whole number'
76
+ });
77
+ });
78
+
79
+ test('bad `observed` > `sample` input', () => {
80
+ assert.throws(() => wilson(11, 10), {
81
+ message: 'Observed must not exceed sample'
27
82
  });
28
83
  });
29
84
  });
30
85
 
31
- describe('handles precision option', () => {
32
- test('wilson(5, 100, false, { precision: 6 })', () => {
33
- const result = wilson(5, 100, false, { precision: 6 });
34
-
35
- assert.deepEqual(result, {
36
- "center": "0.0666474",
37
- "high": "0.111751",
38
- "low": "0.0215437",
86
+ describe('handles `population` arg', () => {
87
+ // Reference values from an independent Python implementation:
88
+ // p unchanged, effective n' = n / ν², ν² = (N − n) / (N − 1).
89
+ test('good `population` input', () => {
90
+ assertInterval(wilson(5, 100, 227), {
91
+ center: 0.05950886403022134,
92
+ high: 0.0925865290106502,
93
+ low: 0.026431199049792478
94
+ });
95
+ });
96
+
97
+ test('`population` = `sample` + 1 with one draw is unadjusted', () => {
98
+ // Exact finite-population factor for n = 1 is 1, so n' = n
99
+ assertInterval(wilson(1, 1, 2), wilson(1, 1));
100
+ });
101
+
102
+ test('`sample` = `population` collapses the interval to p', () => {
103
+ assert.deepEqual(wilson(5, 100, 100), { high: 0.05, center: 0.05, low: 0.05 });
104
+ });
105
+
106
+ test('very large `population` matches no population', () => {
107
+ assertInterval(wilson(5, 100, 1e12), wilson(5, 100));
108
+ });
109
+
110
+ test('bad `population` = 0 input', () => {
111
+ assert.throws(() => wilson(5, 100, 0), {
112
+ message: 'Population must be a positive whole number'
113
+ });
114
+ });
115
+
116
+ test('bad `sample` > `population` input', () => {
117
+ assert.throws(() => wilson(5, 100, 50), {
118
+ message: 'Sample must not exceed population'
39
119
  });
40
120
  });
41
121
  });
42
122
 
43
- describe('handles confidence option', () => {
44
- test('wilson(5, 100, 227, { confidence: 0.9 })', () => {
45
- const result = wilson(5, 100, 227, { confidence: 0.9 });
46
-
47
- assert.deepEqual(result, {
48
- "center": "0.058925960344442384957",
49
- "high": "0.090892465800857729375",
50
- "low": "0.02695945488802704054",
123
+ describe('handles `confidence` arg', () => {
124
+ test('good `confidence` input', () => {
125
+ assertInterval(wilson(5, 100, 227, 0.9), {
126
+ center: 0.05673921186382623,
127
+ high: 0.084248814348019,
128
+ low: 0.02922960937963347
129
+ });
130
+ });
131
+
132
+ test('`confidence` very close to 1 stays finite', () => {
133
+ const result = wilson(5, 100, null, 1 - 1e-16);
134
+ for (const key of ['low', 'center', 'high']) {
135
+ assert.ok(Number.isFinite(result[key]), `${key} is ${result[key]}`);
136
+ }
137
+ assertBounds(result, 0.05);
138
+ });
139
+
140
+ test('bad `confidence` = 1 input', () => {
141
+ assert.throws(() => wilson(5, 100, 227, 1), {
142
+ message: 'Confidence must be a decimal between 0 and 1'
143
+ });
144
+ });
145
+
146
+ test('bad `confidence` = 0 input', () => {
147
+ assert.throws(() => wilson(5, 100, 227, 0), {
148
+ message: 'Confidence must be a decimal between 0 and 1'
149
+ });
150
+ });
151
+
152
+ test('bad `confidence` = "0.9" (string) input', () => {
153
+ assert.throws(() => wilson(5, 100, null, '0.9'), {
154
+ message: 'Confidence must be a decimal between 0 and 1'
51
155
  });
52
156
  });
53
157
  });
54
158
  });
159
+
160
+ describe('normalQuantile()', () => {
161
+ describe('handles basic usage', () => {
162
+ test('good `p` input', () => {
163
+ const result = normalQuantile(0.95);
164
+ assert.strictEqual(result, 1.644853625133699);
165
+ });
166
+
167
+ test('low `p` input', () => {
168
+ const result = normalQuantile(0.01);
169
+ assert.strictEqual(result, -2.326347874388028);
170
+ });
171
+
172
+ test('high `p` input', () => {
173
+ const result = normalQuantile(0.99);
174
+ assert.strictEqual(result, 2.326347874388028);
175
+ });
176
+ });
177
+
178
+ describe('handles edge cases', () => {
179
+ test('`p` = 0 input', () => {
180
+ const result = normalQuantile(0);
181
+ assert.strictEqual(result, -Infinity);
182
+ });
183
+
184
+ test('`p` = 1 input', () => {
185
+ const result = normalQuantile(1);
186
+ assert.strictEqual(result, Infinity);
187
+ });
188
+ });
189
+
190
+ describe('throws on invalid args', () => {
191
+ test('bad `p` < 0 input', () => {
192
+ assert.throws(() => normalQuantile(-1), {
193
+ message: 'p must be a decimal between 0 and 1'
194
+ });
195
+ });
196
+
197
+ test('bad `p` > 1 input', () => {
198
+ assert.throws(() => normalQuantile(2), {
199
+ message: 'p must be a decimal between 0 and 1'
200
+ });
201
+ });
202
+ });
203
+ });