ndarray.js (2739B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2020 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 float64ToFloat32 = require( '@stdlib/number/float64/base/to-float32' ); 24 25 26 // MAIN // 27 28 /** 29 * Computes the variance of a single-precision floating-point strided array ignoring `NaN` values and using Welford's algorithm. 30 * 31 * ## References 32 * 33 * - Welford, B. P. 1962. "Note on a Method for Calculating Corrected Sums of Squares and Products." _Technometrics_ 4 (3). Taylor & Francis: 419–20. doi:[10.1080/00401706.1962.10490022](https://doi.org/10.1080/00401706.1962.10490022). 34 * - van Reeken, A. J. 1968. "Letters to the Editor: Dealing with Neely's Algorithms." _Communications of the ACM_ 11 (3): 149–50. doi:[10.1145/362929.362961](https://doi.org/10.1145/362929.362961). 35 * 36 * @param {PositiveInteger} N - number of indexed elements 37 * @param {number} correction - degrees of freedom adjustment 38 * @param {Float32Array} x - input array 39 * @param {integer} stride - stride length 40 * @param {NonNegativeInteger} offset - starting index 41 * @returns {number} variance 42 * 43 * @example 44 * var Float32Array = require( '@stdlib/array/float32' ); 45 * var floor = require( '@stdlib/math/base/special/floor' ); 46 * 47 * var x = new Float32Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0, NaN, NaN ] ); 48 * var N = floor( x.length / 2 ); 49 * 50 * var v = snanvariancewd( N, 1, x, 2, 1 ); 51 * // returns 6.25 52 */ 53 function snanvariancewd( N, correction, x, stride, offset ) { 54 var delta; 55 var mu; 56 var M2; 57 var ix; 58 var nc; 59 var v; 60 var n; 61 var i; 62 63 if ( N <= 0 ) { 64 return NaN; 65 } 66 if ( N === 1 || stride === 0 ) { 67 v = x[ offset ]; 68 if ( v === v && N-correction > 0.0 ) { 69 return 0.0; 70 } 71 return NaN; 72 } 73 ix = offset; 74 M2 = 0.0; 75 mu = 0.0; 76 n = 0; 77 for ( i = 0; i < N; i++ ) { 78 v = x[ ix ]; 79 if ( v === v ) { 80 delta = float64ToFloat32( v - mu ); 81 n += 1; 82 mu = float64ToFloat32( mu + float64ToFloat32( delta/n ) ); 83 M2 = float64ToFloat32( M2 + float64ToFloat32( delta*float64ToFloat32( v-mu ) ) ); // eslint-disable-line max-len 84 } 85 ix += stride; 86 } 87 nc = n - correction; 88 if ( nc <= 0.0 ) { 89 return NaN; 90 } 91 return float64ToFloat32( M2 / nc ); 92 } 93 94 95 // EXPORTS // 96 97 module.exports = snanvariancewd;