Skip to content

Latest commit

 

History

History
190 lines (121 loc) · 6.26 KB

File metadata and controls

190 lines (121 loc) · 6.26 KB

nanmvariance

Compute a moving unbiased sample variance incrementally, ignoring NaN values.

For a window of size W, the unbiased sample variance is defined as

$$s^2 = \frac{1}{n-1} \sum_{i=0}^{n-1} ( x_i - \bar{x} )^2$$

where n is the number of non-NaN values in the window, and \bar{x} is the arithmetic mean of the non-NaN values.

Usage

var incrnanmvariance = require( '@stdlib/stats/incr/nanmvariance' );

incrnanmvariance( window[, mean] )

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 );

accumulator( [x] )

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

Notes

  • 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 first W-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.

Examples

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() );

See Also