Skip to content

Commit fdc8be1

Browse files
committed
feat: add stats/strided/nanstdevch
Ref: #4797 --- type: pre_commit_static_analysis_report description: Results of running static analysis checks when committing changes. report: - task: lint_filenames status: passed - task: lint_editorconfig status: passed - task: lint_markdown status: passed - task: lint_package_json status: passed - task: lint_repl_help status: passed - task: lint_javascript_src status: passed - task: lint_javascript_cli status: na - task: lint_javascript_examples status: passed - task: lint_javascript_tests status: passed - task: lint_javascript_benchmarks status: passed - task: lint_python status: na - task: lint_r status: na - task: lint_c_src status: na - task: lint_c_examples status: na - task: lint_c_benchmarks status: na - task: lint_c_tests_fixtures status: na - task: lint_shell status: na - task: lint_typescript_declarations status: passed - task: lint_typescript_tests status: passed - task: lint_license_headers status: passed ---
1 parent cf90c43 commit fdc8be1

18 files changed

+2603
-0
lines changed
Lines changed: 283 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,283 @@
1+
<!--
2+
3+
@license Apache-2.0
4+
5+
Copyright (c) 2020 The Stdlib Authors.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
19+
-->
20+
21+
# nanstdevch
22+
23+
> Calculate the [standard deviation][standard-deviation] of a strided array ignoring `NaN` values and using a one-pass trial mean algorithm.
24+
25+
<section class="intro">
26+
27+
The population [standard deviation][standard-deviation] of a finite size population of size `N` is given by
28+
29+
<!-- <equation class="equation" label="eq:population_standard_deviation" align="center" raw="\sigma = \sqrt{\frac{1}{N} \sum_{i=0}^{N-1} (x_i - \mu)^2}" alt="Equation for the population standard deviation."> -->
30+
31+
```math
32+
\sigma = \sqrt{\frac{1}{N} \sum_{i=0}^{N-1} (x_i - \mu)^2}
33+
```
34+
35+
<!-- <div class="equation" align="center" data-raw-text="\sigma = \sqrt{\frac{1}{N} \sum_{i=0}^{N-1} (x_i - \mu)^2}" data-equation="eq:population_standard_deviation">
36+
<img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@e592576989e92b8def74a5fbac9109f3a81f16f9/lib/node_modules/@stdlib/stats/strided/nanstdevch/docs/img/equation_population_standard_deviation.svg" alt="Equation for the population standard deviation.">
37+
<br>
38+
</div> -->
39+
40+
<!-- </equation> -->
41+
42+
where the population mean is given by
43+
44+
<!-- <equation class="equation" label="eq:population_mean" align="center" raw="\mu = \frac{1}{N} \sum_{i=0}^{N-1} x_i" alt="Equation for the population mean."> -->
45+
46+
```math
47+
\mu = \frac{1}{N} \sum_{i=0}^{N-1} x_i
48+
```
49+
50+
<!-- <div class="equation" align="center" data-raw-text="\mu = \frac{1}{N} \sum_{i=0}^{N-1} x_i" data-equation="eq:population_mean">
51+
<img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@e592576989e92b8def74a5fbac9109f3a81f16f9/lib/node_modules/@stdlib/stats/strided/nanstdevch/docs/img/equation_population_mean.svg" alt="Equation for the population mean.">
52+
<br>
53+
</div> -->
54+
55+
<!-- </equation> -->
56+
57+
Often in the analysis of data, the true population [standard deviation][standard-deviation] is not known _a priori_ and must be estimated from a sample drawn from the population distribution. If one attempts to use the formula for the population [standard deviation][standard-deviation], the result is biased and yields an **uncorrected sample standard deviation**. To compute a **corrected sample standard deviation** for a sample of size `n`,
58+
59+
<!-- <equation class="equation" label="eq:corrected_sample_standard_deviation" align="center" raw="s = \sqrt{\frac{1}{n-1} \sum_{i=0}^{n-1} (x_i - \bar{x})^2}" alt="Equation for computing a corrected sample standard deviation."> -->
60+
61+
```math
62+
s = \sqrt{\frac{1}{n-1} \sum_{i=0}^{n-1} (x_i - \bar{x})^2}
63+
```
64+
65+
<!-- <div class="equation" align="center" data-raw-text="s = \sqrt{\frac{1}{n-1} \sum_{i=0}^{n-1} (x_i - \bar{x})^2}" data-equation="eq:corrected_sample_standard_deviation">
66+
<img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@e592576989e92b8def74a5fbac9109f3a81f16f9/lib/node_modules/@stdlib/stats/strided/nanstdevch/docs/img/equation_corrected_sample_standard_deviation.svg" alt="Equation for computing a corrected sample standard deviation.">
67+
<br>
68+
</div> -->
69+
70+
<!-- </equation> -->
71+
72+
where the sample mean is given by
73+
74+
<!-- <equation class="equation" label="eq:sample_mean" align="center" raw="\bar{x} = \frac{1}{n} \sum_{i=0}^{n-1} x_i" alt="Equation for the sample mean."> -->
75+
76+
```math
77+
\bar{x} = \frac{1}{n} \sum_{i=0}^{n-1} x_i
78+
```
79+
80+
<!-- <div class="equation" align="center" data-raw-text="\bar{x} = \frac{1}{n} \sum_{i=0}^{n-1} x_i" data-equation="eq:sample_mean">
81+
<img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@e592576989e92b8def74a5fbac9109f3a81f16f9/lib/node_modules/@stdlib/stats/strided/nanstdevch/docs/img/equation_sample_mean.svg" alt="Equation for the sample mean.">
82+
<br>
83+
</div> -->
84+
85+
<!-- </equation> -->
86+
87+
The use of the term `n-1` is commonly referred to as Bessel's correction. Note, however, that applying Bessel's correction can increase the mean squared error between the sample standard deviation and population standard deviation. Depending on the characteristics of the population distribution, other correction factors (e.g., `n-1.5`, `n+1`, etc) can yield better estimators.
88+
89+
</section>
90+
91+
<!-- /.intro -->
92+
93+
<section class="usage">
94+
95+
## Usage
96+
97+
```javascript
98+
var nanstdevch = require( '@stdlib/stats/strided/nanstdevch' );
99+
```
100+
101+
#### nanstdevch( N, correction, x, strideX )
102+
103+
Computes the [standard deviation][standard-deviation] of a strided array ignoring `NaN` values and using a one-pass trial mean algorithm.
104+
105+
```javascript
106+
var x = [ 1.0, -2.0, NaN, 2.0 ];
107+
108+
var v = nanstdevch( x.length, 1, x, 1 );
109+
// returns ~2.0817
110+
```
111+
112+
The function has the following parameters:
113+
114+
- **N**: number of indexed elements.
115+
- **correction**: degrees of freedom adjustment. Setting this parameter to a value other than `0` has the effect of adjusting the divisor during the calculation of the [standard deviation][standard-deviation] according to `N-c` where `c` corresponds to the provided degrees of freedom adjustment. When computing the [standard deviation][standard-deviation] of a population, setting this parameter to `0` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample [standard deviation][standard-deviation], setting this parameter to `1` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction).
116+
- **x**: input [`Array`][mdn-array] or [`typed array`][mdn-typed-array].
117+
- **strideX**: stride length for `x`.
118+
119+
The `N` and `stride` parameters determine which elements in `x` are accessed at runtime. For example, to compute the [standard deviation][standard-deviation] of every other element in `x`,
120+
121+
```javascript
122+
var x = [ 1.0, 2.0, 2.0, -7.0, -2.0, 3.0, 4.0, 2.0, NaN ];
123+
124+
var v = nanstdevch( 5, 1, x, 2 );
125+
// returns 2.5
126+
```
127+
128+
Note that indexing is relative to the first index. To introduce an offset, use [`typed array`][mdn-typed-array] views.
129+
130+
<!-- eslint-disable stdlib/capitalized-comments, max-len -->
131+
132+
```javascript
133+
var Float64Array = require( '@stdlib/array/float64' );
134+
135+
var x0 = new Float64Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0, NaN, NaN ] );
136+
var x1 = new Float64Array( x0.buffer, x0.BYTES_PER_ELEMENT*1 ); // start at 2nd element
137+
138+
var v = nanstdevch( 5, 1, x1, 2 );
139+
// returns 2.5
140+
```
141+
142+
#### nanstdevch.ndarray( N, correction, x, strideX, offsetX )
143+
144+
Computes the [standard deviation][standard-deviation] of a strided array ignoring `NaN` values and using a one-pass trial mean algorithm and alternative indexing semantics.
145+
146+
```javascript
147+
var x = [ 1.0, -2.0, NaN, 2.0 ];
148+
149+
var v = nanstdevch.ndarray( x.length, 1, x, 1, 0 );
150+
// returns ~2.0817
151+
```
152+
153+
The function has the following additional parameters:
154+
155+
- **offsetX**: starting index for `x`.
156+
157+
While [`typed array`][mdn-typed-array] views mandate a view offset based on the underlying buffer, the offset parameter supports indexing semantics based on a starting index. For example, to calculate the [standard deviation][standard-deviation] for every other element in `x` starting from the second element
158+
159+
```javascript
160+
var x = [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0, NaN, NaN ];
161+
162+
var v = nanstdevch.ndarray( 5, 1, x, 2, 1 );
163+
// returns 2.5
164+
```
165+
166+
</section>
167+
168+
<!-- /.usage -->
169+
170+
<section class="notes">
171+
172+
## Notes
173+
174+
- If `N <= 0`, both functions return `NaN`.
175+
- If `n - c` is less than or equal to `0` (where `c` corresponds to the provided degrees of freedom adjustment and `n` corresponds to the number of non-`NaN` indexed elements), both functions return `NaN`.
176+
- The underlying algorithm is a specialized case of Neely's two-pass algorithm. As the standard deviation is invariant with respect to changes in the location parameter, the underlying algorithm uses the first strided array element as a trial mean to shift subsequent data values and thus mitigate catastrophic cancellation. Accordingly, the algorithm's accuracy is best when data is **unordered** (i.e., the data is **not** sorted in either ascending or descending order such that the first value is an "extreme" value).
177+
- Both functions support array-like objects having getter and setter accessors for array element access (e.g., [`@stdlib/array/base/accessor`][@stdlib/array/base/accessor]).
178+
- Depending on the environment, the typed versions ([`dnanstdevch`][@stdlib/stats/strided/dnanstdevch], [`snanstdevch`][@stdlib/stats/base/snanstdevch], etc.) are likely to be significantly more performant.
179+
180+
</section>
181+
182+
<!-- /.notes -->
183+
184+
<section class="examples">
185+
186+
## Examples
187+
188+
<!-- eslint no-undef: "error" -->
189+
190+
```javascript
191+
var uniform = require( '@stdlib/random/base/uniform' );
192+
var filledarrayBy = require( '@stdlib/array/filled-by' );
193+
var bernoulli = require( '@stdlib/random/base/bernoulli' );
194+
var nanstdevch = require( '@stdlib/stats/strided/nanstdevch' );
195+
196+
function rand() {
197+
if ( bernoulli( 0.8 ) < 1 ) {
198+
return NaN;
199+
}
200+
return uniform( -50.0, 50.0 );
201+
}
202+
203+
var x = filledarrayBy( 10, 'float64', rand );
204+
console.log( x );
205+
206+
var v = nanstdevch( x.length, 1, x, 1 );
207+
console.log( v );
208+
```
209+
210+
</section>
211+
212+
<!-- /.examples -->
213+
214+
* * *
215+
216+
<section class="references">
217+
218+
## References
219+
220+
- Neely, Peter M. 1966. "Comparison of Several Algorithms for Computation of Means, Standard Deviations and Correlation Coefficients." _Communications of the ACM_ 9 (7). Association for Computing Machinery: 496–99. doi:[10.1145/365719.365958][@neely:1966a].
221+
- Ling, Robert F. 1974. "Comparison of Several Algorithms for Computing Sample Means and Variances." _Journal of the American Statistical Association_ 69 (348). American Statistical Association, Taylor & Francis, Ltd.: 859–66. doi:[10.2307/2286154][@ling:1974a].
222+
- Chan, Tony F., Gene H. Golub, and Randall J. LeVeque. 1983. "Algorithms for Computing the Sample Variance: Analysis and Recommendations." _The American Statistician_ 37 (3). American Statistical Association, Taylor & Francis, Ltd.: 242–47. doi:[10.1080/00031305.1983.10483115][@chan:1983a].
223+
- Schubert, Erich, and Michael Gertz. 2018. "Numerically Stable Parallel Computation of (Co-)Variance." In _Proceedings of the 30th International Conference on Scientific and Statistical Database Management_. New York, NY, USA: Association for Computing Machinery. doi:[10.1145/3221269.3223036][@schubert:2018a].
224+
225+
</section>
226+
227+
<!-- /.references -->
228+
229+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
230+
231+
<section class="related">
232+
233+
* * *
234+
235+
## See Also
236+
237+
- <span class="package-name">[`@stdlib/stats/strided/dnanstdevch`][@stdlib/stats/strided/dnanstdevch]</span><span class="delimiter">: </span><span class="description">calculate the standard deviation of a double-precision floating-point strided array ignoring NaN values and using a one-pass trial mean algorithm.</span>
238+
- <span class="package-name">[`@stdlib/stats/strided/nanvariancech`][@stdlib/stats/strided/nanvariancech]</span><span class="delimiter">: </span><span class="description">calculate the variance of a strided array ignoring NaN values and using a one-pass trial mean algorithm.</span>
239+
- <span class="package-name">[`@stdlib/stats/base/nanstdev`][@stdlib/stats/base/nanstdev]</span><span class="delimiter">: </span><span class="description">calculate the standard deviation of a strided array ignoring NaN values.</span>
240+
- <span class="package-name">[`@stdlib/stats/base/snanstdevch`][@stdlib/stats/base/snanstdevch]</span><span class="delimiter">: </span><span class="description">calculate the standard deviation of a single-precision floating-point strided array ignoring NaN values and using a one-pass trial mean algorithm.</span>
241+
- <span class="package-name">[`@stdlib/stats/strided/stdevch`][@stdlib/stats/strided/stdevch]</span><span class="delimiter">: </span><span class="description">calculate the standard deviation of a strided array using a one-pass trial mean algorithm.</span>
242+
243+
</section>
244+
245+
<!-- /.related -->
246+
247+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
248+
249+
<section class="links">
250+
251+
[standard-deviation]: https://en.wikipedia.org/wiki/Standard_deviation
252+
253+
[mdn-array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
254+
255+
[mdn-typed-array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
256+
257+
[@stdlib/array/base/accessor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/array/base/accessor
258+
259+
[@neely:1966a]: https://doi.org/10.1145/365719.365958
260+
261+
[@ling:1974a]: https://doi.org/10.2307/2286154
262+
263+
[@chan:1983a]: https://doi.org/10.1080/00031305.1983.10483115
264+
265+
[@schubert:2018a]: https://doi.org/10.1145/3221269.3223036
266+
267+
<!-- <related-links> -->
268+
269+
[@stdlib/stats/strided/dnanstdevch]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/stats/strided/dnanstdevch
270+
271+
[@stdlib/stats/strided/nanvariancech]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/stats/strided/nanvariancech
272+
273+
[@stdlib/stats/base/nanstdev]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/stats/base/nanstdev
274+
275+
[@stdlib/stats/base/snanstdevch]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/stats/base/snanstdevch
276+
277+
[@stdlib/stats/strided/stdevch]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/stats/strided/stdevch
278+
279+
<!-- </related-links> -->
280+
281+
</section>
282+
283+
<!-- /.links -->
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2020 The Stdlib Authors.
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
'use strict';
20+
21+
// MODULES //
22+
23+
var bench = require( '@stdlib/bench' );
24+
var uniform = require( '@stdlib/random/base/uniform' );
25+
var bernoulli = require( '@stdlib/random/base/bernoulli' );
26+
var filledarrayBy = require( '@stdlib/array/filled-by' );
27+
var isnan = require( '@stdlib/math/base/assert/is-nan' );
28+
var pow = require( '@stdlib/math/base/special/pow' );
29+
var pkg = require( './../package.json' ).name;
30+
var nanstdevch = require( './../lib' );
31+
32+
33+
// FUNCTIONS //
34+
35+
/**
36+
* Returns a random number.
37+
*
38+
* @private
39+
* @returns {number} random number
40+
*/
41+
function rand() {
42+
if ( bernoulli( 0.8 ) < 1 ) {
43+
return NaN;
44+
}
45+
return uniform( -10.0, 10.0 );
46+
}
47+
48+
/**
49+
* Creates a benchmark function.
50+
*
51+
* @private
52+
* @param {PositiveInteger} len - array length
53+
* @returns {Function} benchmark function
54+
*/
55+
function createBenchmark( len ) {
56+
var x = filledarrayBy( len, 'generic', rand );
57+
return benchmark;
58+
59+
function benchmark( b ) {
60+
var v;
61+
var i;
62+
63+
b.tic();
64+
for ( i = 0; i < b.iterations; i++ ) {
65+
v = nanstdevch( x.length, 1, x, 1 );
66+
if ( isnan( v ) ) {
67+
b.fail( 'should not return NaN' );
68+
}
69+
}
70+
b.toc();
71+
if ( isnan( v ) ) {
72+
b.fail( 'should not return NaN' );
73+
}
74+
b.pass( 'benchmark finished' );
75+
b.end();
76+
}
77+
}
78+
79+
80+
// MAIN //
81+
82+
/**
83+
* Main execution sequence.
84+
*
85+
* @private
86+
*/
87+
function main() {
88+
var len;
89+
var min;
90+
var max;
91+
var f;
92+
var i;
93+
94+
min = 1; // 10^min
95+
max = 6; // 10^max
96+
97+
for ( i = min; i <= max; i++ ) {
98+
len = pow( 10, i );
99+
f = createBenchmark( len );
100+
bench( pkg+':len='+len, f );
101+
}
102+
}
103+
104+
main();

0 commit comments

Comments
 (0)