Skip to content

Commit 5db4a49

Browse files
committed
feat: add stats/base/ndarray/svariance
--- 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 040d8ec commit 5db4a49

File tree

10 files changed

+941
-0
lines changed

10 files changed

+941
-0
lines changed
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
<!--
2+
3+
@license Apache-2.0
4+
5+
Copyright (c) 2025 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+
# svariance
22+
23+
> Calculate the [variance][variance] of a one-dimensional single-precision floating-point ndarray.
24+
25+
<section class="intro">
26+
27+
The population [variance][variance] of a finite size population of size `N` is given by
28+
29+
<!-- <equation class="equation" label="eq:population_variance" align="center" raw="\sigma^2 = \frac{1}{N} \sum_{i=0}^{N-1} (x_i - \mu)^2" alt="Equation for the population variance."> -->
30+
31+
```math
32+
\sigma^2 = \frac{1}{N} \sum_{i=0}^{N-1} (x_i - \mu)^2
33+
```
34+
35+
<!-- <div class="equation" align="center" data-raw-text="\sigma^2 = \frac{1}{N} \sum_{i=0}^{N-1} (x_i - \mu)^2" data-equation="eq:population_variance">
36+
<img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@08ca32895957967bd760a4fe02d61762432a0b72/lib/node_modules/@stdlib/stats/strided/svariance/docs/img/equation_population_variance.svg" alt="Equation for the population variance.">
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@08ca32895957967bd760a4fe02d61762432a0b72/lib/node_modules/@stdlib/stats/strided/svariance/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 [variance][variance] 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 [variance][variance], the result is biased and yields an **uncorrected sample variance**. To compute a **corrected sample variance** for a sample of size `n`,
58+
59+
<!-- <equation class="equation" label="eq:corrected_sample_variance" align="center" raw="s^2 = \frac{1}{n-1} \sum_{i=0}^{n-1} (x_i - \bar{x})^2" alt="Equation for computing a corrected sample variance."> -->
60+
61+
```math
62+
s^2 = \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^2 = \frac{1}{n-1} \sum_{i=0}^{n-1} (x_i - \bar{x})^2" data-equation="eq:corrected_sample_variance">
66+
<img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@08ca32895957967bd760a4fe02d61762432a0b72/lib/node_modules/@stdlib/stats/strided/svariance/docs/img/equation_corrected_sample_variance.svg" alt="Equation for computing a corrected sample variance.">
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@08ca32895957967bd760a4fe02d61762432a0b72/lib/node_modules/@stdlib/stats/strided/svariance/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 variance and population variance. 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 svariance = require( '@stdlib/stats/base/ndarray/svariance' );
99+
```
100+
101+
#### svariance( arrays )
102+
103+
Computes the [variance][variance] of a one-dimensional single-precision floating-point ndarray.
104+
105+
```javascript
106+
var Float32Array = require( '@stdlib/array/float32' );
107+
var scalar2ndarray = require( '@stdlib/ndarray/from-scalar' );
108+
var ndarray = require( '@stdlib/ndarray/base/ctor' );
109+
110+
var opts = {
111+
'dtype': 'float32'
112+
};
113+
114+
var xbuf = new Float32Array( [ 1.0, -2.0, 2.0 ] );
115+
var x = new ndarray( opts.dtype, xbuf, [ 3 ], [ 1 ], 0, 'row-major' );
116+
117+
var correction = scalar2ndarray( 1.0, opts );
118+
119+
var v = svariance( [ x, correction ] );
120+
// returns ~4.333333
121+
```
122+
123+
The function accepts the following arguments:
124+
125+
- **arrays**: array-like object containing a one-dimensional input ndarray and a zero-dimensional ndarray specifying a degrees of freedom adjustment.
126+
127+
The function assumes that the input ndarray has a single-precision floating-point data type `float32`.
128+
129+
</section>
130+
131+
<!-- /.usage -->
132+
133+
<section class="examples">
134+
135+
## Examples
136+
137+
<!-- eslint no-undef: "error" -->
138+
139+
```javascript
140+
var Float32Array = require( '@stdlib/array/float32' );
141+
var scalar2ndarray = require( '@stdlib/ndarray/from-scalar' );
142+
var ndarray = require( '@stdlib/ndarray/base/ctor' );
143+
var svariance = require( '@stdlib/stats/base/ndarray/svariance' );
144+
145+
var opts = {
146+
'dtype': 'float32'
147+
};
148+
149+
var xbuf = new Float32Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ] );
150+
var x = new ndarray( opts.dtype, xbuf, [ 4 ], [ 2 ], 1, 'row-major' );
151+
152+
var correction = scalar2ndarray( 1.0, opts );
153+
154+
var v = svariance( [ x, correction ] );
155+
// returns 6.25
156+
```
157+
158+
</section>
159+
160+
<!-- /.examples -->
161+
162+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
163+
164+
<section class="related">
165+
166+
</section>
167+
168+
<!-- /.related -->
169+
170+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
171+
172+
<section class="links">
173+
174+
[variance]: https://en.wikipedia.org/wiki/Variance
175+
176+
</section>
177+
178+
<!-- /.links -->
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2025 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/array/uniform' );
25+
var isnanf = require( '@stdlib/math/base/assert/is-nanf' );
26+
var pow = require( '@stdlib/math/base/special/pow' );
27+
var ndarray = require( '@stdlib/ndarray/base/ctor' );
28+
var scalar2ndarray = require( '@stdlib/ndarray/from-scalar' );
29+
var format = require( '@stdlib/string/format' );
30+
var pkg = require( './../package.json' ).name;
31+
var svariance = require( './../lib' );
32+
33+
34+
// VARIABLES //
35+
36+
var options = {
37+
'dtype': 'float32'
38+
};
39+
40+
41+
// FUNCTIONS //
42+
43+
/**
44+
* Creates a benchmark function.
45+
*
46+
* @private
47+
* @param {PositiveInteger} len - array length
48+
* @returns {Function} benchmark function
49+
*/
50+
function createBenchmark( len ) {
51+
var correction;
52+
var xbuf;
53+
var x;
54+
55+
xbuf = uniform( len, -10.0, 10.0, options );
56+
x = new ndarray( options.dtype, xbuf, [ len ], [ 1 ], 0, 'row-major' );
57+
correction = scalar2ndarray( 1.0, options );
58+
59+
return benchmark;
60+
61+
function benchmark( b ) {
62+
var v;
63+
var i;
64+
65+
b.tic();
66+
for ( i = 0; i < b.iterations; i++ ) {
67+
v = svariance( [ x, correction ] );
68+
if ( isnanf( v ) ) {
69+
b.fail( 'should not return NaN' );
70+
}
71+
}
72+
b.toc();
73+
if ( isnanf( v ) ) {
74+
b.fail( 'should not return NaN' );
75+
}
76+
b.pass( 'benchmark finished' );
77+
b.end();
78+
}
79+
}
80+
81+
82+
// MAIN //
83+
84+
/**
85+
* Main execution sequence.
86+
*
87+
* @private
88+
*/
89+
function main() {
90+
var len;
91+
var min;
92+
var max;
93+
var f;
94+
var i;
95+
96+
min = 1; // 10^min
97+
max = 6; // 10^max
98+
99+
for ( i = min; i <= max; i++ ) {
100+
len = pow( 10, i );
101+
f = createBenchmark( len );
102+
bench( format( '%s:len=%d', pkg, len ), f );
103+
}
104+
}
105+
106+
main();
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
{{alias}}( arrays )
3+
Computes the variance of a one-dimensional single-precision
4+
floating-point ndarray.
5+
6+
Parameters
7+
----------
8+
arrays: Array<ndarray>
9+
Array-like object containing a one-dimensional input ndarray and a
10+
zero-dimensional ndarray specifying a degrees of freedom adjustment.
11+
12+
Returns
13+
-------
14+
out: number
15+
The variance.
16+
17+
Examples
18+
--------
19+
// Standard Usage:
20+
> var Float32Array = require( '@stdlib/array/float32' );
21+
> var scalar2ndarray = require( '@stdlib/ndarray/from-scalar' );
22+
> var ndarray = require( '@stdlib/ndarray/base/ctor' );
23+
> var xbuf = new Float32Array( [ 1.0, -2.0, 2.0 ] );
24+
> var x = new ndarray( 'float32', xbuf, [ 3 ], [ 1 ], 0, 'row-major' );
25+
> var correction = scalar2ndarray( 1.0, { 'dtype': 'float32' } );
26+
> {{alias}}( [ x, correction ] )
27+
~4.333333
28+
29+
// Using ndarray properties:
30+
> xbuf = new Float32Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ] );
31+
> x = new ndarray( 'float32', xbuf, [ 4 ], [ 2 ], 1, 'row-major' );
32+
> correction = scalar2ndarray( 1.0, { 'dtype': 'float32' } );
33+
> {{alias}}( [ x, correction ] )
34+
6.25
35+
36+
See Also
37+
--------
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2025 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+
// TypeScript Version: 4.1
20+
21+
/// <reference types="@stdlib/types"/>
22+
23+
import { float32ndarray, typedndarray } from '@stdlib/types/ndarray';
24+
25+
/**
26+
* Computes the variance of a one-dimensional ndarray.
27+
*
28+
* @param arrays - array-like object containing a one-dimensional input ndarray and a zero-dimensional ndarray specifying a degrees of freedom adjustment
29+
* @returns variance
30+
*
31+
* @example
32+
* var ndarray = require( '@stdlib/ndarray/base/ctor' );
33+
* var scalar2ndarray = require( '@stdlib/ndarray/from-scalar' );
34+
* var Float32Array = require( '@stdlib/array/float32' );
35+
*
36+
* var opts = {
37+
* 'dtype': 'float32'
38+
* };
39+
*
40+
* var xbuf = new Float32Array( [ 1.0, -2.0, 2.0 ] );
41+
* var x = new ndarray( opts.dtype, xbuf, [ 3 ], [ 1 ], 0, 'row-major' );
42+
* var correction = scalar2ndarray( 1.0, opts );
43+
*
44+
* var v = svariance( [ x, correction ] );
45+
* // returns ~4.333333
46+
*/
47+
declare function svariance<T extends typedndarray<number> = typedndarray<number>>( arrays: [ float32ndarray, T ] ): number;
48+
49+
50+
// EXPORTS //
51+
52+
export = svariance;

0 commit comments

Comments
 (0)