Skip to content

Commit 3a07ca1

Browse files
Sachinn-64kgryte
andauthored
feat: add stats/meanwd
PR-URL: stdlib-js#8914 Co-authored-by: Athan Reines <kgryte@gmail.com> Reviewed-by: Athan Reines <kgryte@gmail.com>
1 parent 01a7d5e commit 3a07ca1

File tree

13 files changed

+2697
-0
lines changed

13 files changed

+2697
-0
lines changed
Lines changed: 268 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,268 @@
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+
# meanwd
22+
23+
> Compute the [arithmetic mean][arithmetic-mean] along one or more [ndarray][@stdlib/ndarray/ctor] dimensions using Welford's algorithm.
24+
25+
<section class="intro">
26+
27+
The [arithmetic mean][arithmetic-mean] is defined as
28+
29+
<!-- <equation class="equation" label="eq:arithmetic_mean" align="center" raw="\mu = \frac{1}{n} \sum_{i=0}^{n-1} x_i" alt="Equation for the arithmetic mean."> -->
30+
31+
```math
32+
\mu = \frac{1}{n} \sum_{i=0}^{n-1} x_i
33+
```
34+
35+
<!-- <div class="equation" align="center" data-raw-text="\mu = \frac{1}{n} \sum_{i=0}^{n-1} x_i" data-equation="eq:arithmetic_mean">
36+
<img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@42d8f64d805113ab899c79c7c39d6c6bac7fe25c/lib/node_modules/@stdlib/stats/strided/meanwd/docs/img/equation_arithmetic_mean.svg" alt="Equation for the arithmetic mean.">
37+
<br>
38+
</div> -->
39+
40+
<!-- </equation> -->
41+
42+
</section>
43+
44+
<!-- /.intro -->
45+
46+
<section class="usage">
47+
48+
## Usage
49+
50+
```javascript
51+
var meanwd = require( '@stdlib/stats/meanwd' );
52+
```
53+
54+
#### meanwd( x\[, options] )
55+
56+
Computes the [arithmetic mean][arithmetic-mean] along one or more [ndarray][@stdlib/ndarray/ctor] dimensions using Welford's algorithm.
57+
58+
```javascript
59+
var array = require( '@stdlib/ndarray/array' );
60+
61+
var x = array( [ 1.0, 2.0, -2.0, 4.0 ] );
62+
63+
var y = meanwd( x );
64+
// returns <ndarray>[ 1.25 ]
65+
```
66+
67+
The function has the following parameters:
68+
69+
- **x**: input [ndarray][@stdlib/ndarray/ctor]. Must have a real-valued or "generic" [data type][@stdlib/ndarray/dtypes].
70+
- **options**: function options (_optional_).
71+
72+
The function accepts the following options:
73+
74+
- **dims**: list of dimensions over which to perform a reduction. If not provided, the function performs a reduction over all elements in a provided input [ndarray][@stdlib/ndarray/ctor].
75+
- **dtype**: output ndarray [data type][@stdlib/ndarray/dtypes]. Must be a real-valued floating-point or "generic" [data type][@stdlib/ndarray/dtypes].
76+
- **keepdims**: boolean indicating whether the reduced dimensions should be included in the returned [ndarray][@stdlib/ndarray/ctor] as singleton dimensions. Default: `false`.
77+
78+
By default, the function performs a reduction over all elements in a provided input [ndarray][@stdlib/ndarray/ctor]. To perform a reduction over specific dimensions, provide a `dims` option.
79+
80+
```javascript
81+
var array = require( '@stdlib/ndarray/array' );
82+
83+
var x = array( [ 1.0, 2.0, -2.0, 4.0 ], {
84+
'shape': [ 2, 2 ],
85+
'order': 'row-major'
86+
});
87+
// returns <ndarray>[ [ 1.0, 2.0 ], [ -2.0, 4.0 ] ]
88+
89+
var y = meanwd( x, {
90+
'dims': [ 0 ]
91+
});
92+
// returns <ndarray>[ -0.5, 3.0 ]
93+
94+
y = meanwd( x, {
95+
'dims': [ 1 ]
96+
});
97+
// returns <ndarray>[ 1.5, 1.0 ]
98+
99+
y = meanwd( x, {
100+
'dims': [ 0, 1 ]
101+
});
102+
// returns <ndarray>[ 1.25 ]
103+
```
104+
105+
By default, the function excludes reduced dimensions from the output [ndarray][@stdlib/ndarray/ctor]. To include the reduced dimensions as singleton dimensions, set the `keepdims` option to `true`.
106+
107+
```javascript
108+
var array = require( '@stdlib/ndarray/array' );
109+
110+
var x = array( [ 1.0, 2.0, -2.0, 4.0 ], {
111+
'shape': [ 2, 2 ],
112+
'order': 'row-major'
113+
});
114+
// returns <ndarray>[ [ 1.0, 2.0 ], [ -2.0, 4.0 ] ]
115+
116+
var y = meanwd( x, {
117+
'dims': [ 0 ],
118+
'keepdims': true
119+
});
120+
// returns <ndarray>[ [ -0.5, 3.0 ] ]
121+
122+
y = meanwd( x, {
123+
'dims': [ 1 ],
124+
'keepdims': true
125+
});
126+
// returns <ndarray>[ [ 1.5 ], [ 1.0 ] ]
127+
128+
y = meanwd( x, {
129+
'dims': [ 0, 1 ],
130+
'keepdims': true
131+
});
132+
// returns <ndarray>[ [ 1.25 ] ]
133+
```
134+
135+
By default, the function returns an [ndarray][@stdlib/ndarray/ctor] having a [data type][@stdlib/ndarray/dtypes] determined by the function's output data type [policy][@stdlib/ndarray/output-dtype-policies]. To override the default behavior, set the `dtype` option.
136+
137+
```javascript
138+
var getDType = require( '@stdlib/ndarray/dtype' );
139+
var array = require( '@stdlib/ndarray/array' );
140+
141+
var x = array( [ 1.0, 2.0, -2.0, 4.0 ], {
142+
'dtype': 'generic'
143+
});
144+
145+
var y = meanwd( x, {
146+
'dtype': 'float64'
147+
});
148+
// returns <ndarray>[ 1.25 ]
149+
150+
var dt = String( getDType( y ) );
151+
// returns 'float64'
152+
```
153+
154+
#### meanwd.assign( x, out\[, options] )
155+
156+
Computes the [arithmetic mean][arithmetic-mean] along one or more [ndarray][@stdlib/ndarray/ctor] dimensions using Welford's algorithm and assigns results to a provided output [ndarray][@stdlib/ndarray/ctor].
157+
158+
```javascript
159+
var array = require( '@stdlib/ndarray/array' );
160+
var zeros = require( '@stdlib/ndarray/zeros' );
161+
162+
var x = array( [ 1.0, 2.0, -2.0, 4.0 ] );
163+
var y = zeros( [] );
164+
165+
var out = meanwd.assign( x, y );
166+
// returns <ndarray>[ 1.25 ]
167+
168+
var bool = ( out === y );
169+
// returns true
170+
```
171+
172+
The method has the following parameters:
173+
174+
- **x**: input [ndarray][@stdlib/ndarray/ctor]. Must have a real-valued or generic [data type][@stdlib/ndarray/dtypes].
175+
- **out**: output [ndarray][@stdlib/ndarray/ctor].
176+
- **options**: function options (_optional_).
177+
178+
The method accepts the following options:
179+
180+
- **dims**: list of dimensions over which to perform a reduction. If not provided, the function performs a reduction over all elements in a provided input [ndarray][@stdlib/ndarray/ctor].
181+
182+
</section>
183+
184+
<!-- /.usage -->
185+
186+
<section class="notes">
187+
188+
## Notes
189+
190+
- Setting the `keepdims` option to `true` can be useful when wanting to ensure that the output [ndarray][@stdlib/ndarray/ctor] is [broadcast-compatible][@stdlib/ndarray/base/broadcast-shapes] with ndarrays having the same shape as the input [ndarray][@stdlib/ndarray/ctor].
191+
- The output data type [policy][@stdlib/ndarray/output-dtype-policies] only applies to the main function and specifies that, by default, the function must return an [ndarray][@stdlib/ndarray/ctor] having a real-valued floating-point or "generic" [data type][@stdlib/ndarray/dtypes]. For the `assign` method, the output [ndarray][@stdlib/ndarray/ctor] is allowed to have any supported output [data type][@stdlib/ndarray/dtypes].
192+
193+
</section>
194+
195+
<!-- /.notes -->
196+
197+
<section class="examples">
198+
199+
## Examples
200+
201+
<!-- eslint no-undef: "error" -->
202+
203+
```javascript
204+
var uniform = require( '@stdlib/random/uniform' );
205+
var getDType = require( '@stdlib/ndarray/dtype' );
206+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
207+
var meanwd = require( '@stdlib/stats/meanwd' );
208+
209+
// Generate an array of random numbers:
210+
var x = uniform( [ 5, 5 ], 0.0, 20.0 );
211+
console.log( ndarray2array( x ) );
212+
213+
// Perform a reduction:
214+
var y = meanwd( x, {
215+
'dims': [ 0 ]
216+
});
217+
218+
// Resolve the output array data type:
219+
var dt = getDType( y );
220+
console.log( dt );
221+
222+
// Print the results:
223+
console.log( ndarray2array( y ) );
224+
```
225+
226+
</section>
227+
228+
<!-- /.examples -->
229+
230+
* * *
231+
232+
<section class="references">
233+
234+
## References
235+
236+
- Welford, B. P. 1962. "Note on a Method for Calculating Corrected Sums of Squares and Products." _Technometrics_ 4 (3): 419–20. doi:[10.1080/00401706.1962.10490022][@welford:1962a].
237+
238+
</section>
239+
240+
<!-- /.references -->
241+
242+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
243+
244+
<section class="related">
245+
246+
</section>
247+
248+
<!-- /.related -->
249+
250+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
251+
252+
<section class="links">
253+
254+
[@stdlib/ndarray/ctor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/ctor
255+
256+
[@stdlib/ndarray/dtypes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/dtypes
257+
258+
[@stdlib/ndarray/output-dtype-policies]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/output-dtype-policies
259+
260+
[@stdlib/ndarray/base/broadcast-shapes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/base/broadcast-shapes
261+
262+
[@welford:1962a]: https://doi.org/10.1080/00401706.1962.10490022
263+
264+
[arithmetic-mean]: https://en.wikipedia.org/wiki/Arithmetic_mean
265+
266+
</section>
267+
268+
<!-- /.links -->
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
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 isnan = require( '@stdlib/math/base/assert/is-nan' );
25+
var pow = require( '@stdlib/math/base/special/pow' );
26+
var uniform = require( '@stdlib/random/array/uniform' );
27+
var zeros = require( '@stdlib/array/zeros' );
28+
var ndarray = require( '@stdlib/ndarray/base/ctor' );
29+
var pkg = require( './../package.json' ).name;
30+
var meanwd = require( './../lib' );
31+
32+
33+
// VARIABLES //
34+
35+
var options = {
36+
'dtype': 'float64'
37+
};
38+
39+
40+
// FUNCTIONS //
41+
42+
/**
43+
* Creates a benchmark function.
44+
*
45+
* @private
46+
* @param {PositiveInteger} len - array length
47+
* @returns {Function} benchmark function
48+
*/
49+
function createBenchmark( len ) {
50+
var out;
51+
var x;
52+
53+
x = uniform( len, -50.0, 50.0, options );
54+
x = new ndarray( options.dtype, x, [ len ], [ 1 ], 0, 'row-major' );
55+
56+
out = new ndarray( options.dtype, zeros( 1, options.dtype ), [], [ 0 ], 0, 'row-major' );
57+
58+
return benchmark;
59+
60+
/**
61+
* Benchmark function.
62+
*
63+
* @private
64+
* @param {Benchmark} b - benchmark instance
65+
*/
66+
function benchmark( b ) {
67+
var o;
68+
var i;
69+
70+
b.tic();
71+
for ( i = 0; i < b.iterations; i++ ) {
72+
o = meanwd.assign( x, out );
73+
if ( typeof o !== 'object' ) {
74+
b.fail( 'should return an ndarray' );
75+
}
76+
}
77+
b.toc();
78+
if ( isnan( o.get() ) ) {
79+
b.fail( 'should not return NaN' );
80+
}
81+
b.pass( 'benchmark finished' );
82+
b.end();
83+
}
84+
}
85+
86+
87+
// MAIN //
88+
89+
/**
90+
* Main execution sequence.
91+
*
92+
* @private
93+
*/
94+
function main() {
95+
var len;
96+
var min;
97+
var max;
98+
var f;
99+
var i;
100+
101+
min = 1; // 10^min
102+
max = 6; // 10^max
103+
104+
for ( i = min; i <= max; i++ ) {
105+
len = pow( 10, i );
106+
f = createBenchmark( len );
107+
bench( pkg+':assign:dtype='+options.dtype+',len='+len, f );
108+
}
109+
}
110+
111+
main();

0 commit comments

Comments
 (0)