Compute a moving unbiased sample variance incrementally, ignoring
NaN
values.
For a window of size W
, the unbiased sample variance is defined as
where n
is the number of non-NaN
values in the window, and \bar{x}
is the arithmetic mean of the non-NaN
values.
var incrnanmvariance = require( '@stdlib/stats/incr/nanmvariance' );
Returns an accumulator function
which incrementally computes a moving unbiased sample variance, ignoring NaN
values. The window
parameter defines the number of values over which to compute the moving unbiased sample variance.
var accumulator = incrnanmvariance( 3 );
If the mean is already known, provide a mean
argument.
var accumulator = incrnanmvariance( 3, 5.0 );
If provided an input value x
, the accumulator function returns an updated unbiased sample variance. If not provided an input value x
, the accumulator function returns the current unbiased sample variance.
var accumulator = incrnanmvariance( 3 );
var s2 = accumulator();
// returns null
// Fill the window...
s2 = accumulator( 2.0 ); // [2.0]
// returns 0.0
s2 = accumulator( NaN ); // [2.0, NaN]
// returns 0.0
s2 = accumulator( -5.0 ); // [2.0, NaN, -5.0]
// returns 24.5
// Window begins sliding...
s2 = accumulator( 3.0 ); // [NaN, -5.0, 3.0]
// returns 19.0
s2 = accumulator( NaN ); // [-5.0, 3.0, NaN]
// returns 19.0
s2 = accumulator();
// returns 19.0
- Input values are not type checked. If non-numeric inputs are possible, you are advised to type check and handle accordingly before passing the value to the accumulator function.
- NaN input values are ignored. If the window contains only NaN values, the variance is calculated as if the window were empty.
- As
W
values are needed to fill the window buffer, the firstW-1
returned values are calculated from smaller sample sizes. Until the window is full, each returned value is calculated from all provided non-NaN values. - The implementation uses Welford's algorithm.
var randu = require( '@stdlib/random/base/randu' );
var incrnanmvariance = require( '@stdlib/stats/incr/nanmvariance' );
var accumulator;
var v;
var i;
// Initialize an accumulator:
accumulator = incrnanmvariance( 5 );
// For each simulated datum, update the moving unbiased sample variance...
console.log( '\nValue\tSample Variance\n' );
for ( i = 0; i < 100; i++ ) {
if ( randu() < 0.2 ) {
v = NaN;
} else {
v = randu() * 100.0;
}
console.log( '%d\t%d', v.toFixed( 4 ), accumulator( v ).toFixed( 4 ) );
}
console.log( '\nFinal variance: %d\n', accumulator() );
@stdlib/stats/incr/mvariance
: compute a moving unbiased sample variance incrementally.@stdlib/stats/incr/nanmmean
: compute a moving arithmetic mean incrementally, ignoring NaN values.@stdlib/stats/incr/nanmstdev
: compute a moving corrected sample standard deviation incrementally, ignoring NaN values.@stdlib/stats/incr/nanvariance
: compute an unbiased sample variance incrementally, ignoring NaN values.