Skip to content

Latest commit

 

History

History
159 lines (100 loc) · 4.58 KB

File metadata and controls

159 lines (100 loc) · 4.58 KB

incrnanmvariance

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}{W-1} \sum_{i=0}^{W-1} ( x_i - \bar{x} )^2$$

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. If provided NaN, the accumulator function ignores the value and returns the current unbiased sample variance without updating the window.

var accumulator = incrnanmvariance( 3 );

var s2 = accumulator();
// returns null

// Fill the window with non-NaN values...
s2 = accumulator( 2.0 ); // [2.0]
// returns 0.0

// NaN ignored...
s2 = accumulator( NaN );
// returns 0.0

s2 = accumulator( -5.0 ); // [2.0, -5.0]
// returns 24.5

s2 = accumulator( 3.0 ); // [2.0, -5.0, 3.0]
// returns 19.0

// NaN ignored...
s2 = accumulator( NaN );
// returns 19.0

s2 = accumulator();
// returns 19.0

Notes

  • NaN values are ignored. If all values in the window are NaN, the accumulator returns the last valid variance or null if no valid values have been provided.
  • Input values are not type checked beyond NaN detection. If other non-numeric inputs are possible, you are advised to type check and handle accordingly before passing the value to the accumulator function.
  • 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.

Examples

var uniform = require( '@stdlib/random/base/uniform' );
var bernoulli = require( '@stdlib/random/base/bernoulli' );
var incrnanmvariance = require( '@stdlib/stats/incr/nanmvariance' );

// Initialize an accumulator:
var accumulator = incrnanmvariance( 5 );

// For each simulated datum, update the moving variance...
var i;
for ( i = 0; i < 100; i++ ) {
    accumulator( ( bernoulli( 0.8 ) < 1 ) ? NaN : uniform( -50.0, 50.0 ) );
}
console.log( accumulator() );