main.js (2317B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 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 isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive; 24 25 26 // MAIN // 27 28 /** 29 * Returns an accumulator function which incrementally computes an exponentially weighted variance. 30 * 31 * @param {NonNegativeNumber} alpha - smoothing factor 32 * @throws {TypeError} must provide a nonnegative number 33 * @throws {RangeError} must be on the interval `[0,1]` 34 * @returns {Function} accumulator function 35 * 36 * @example 37 * var accumulator = increwvariance( 0.5 ); 38 * 39 * var v = accumulator(); 40 * // returns null 41 * 42 * v = accumulator( 2.0 ); 43 * // returns 0.0 44 * 45 * v = accumulator( -5.0 ); 46 * // returns 12.25 47 * 48 * v = accumulator(); 49 * // returns 12.25 50 */ 51 function increwvariance( alpha ) { 52 var incr; 53 var s2; 54 var r; 55 var m; 56 var c; 57 if ( !isNonNegativeNumber( alpha ) ) { 58 throw new TypeError( 'invalid argument. Must provide a nonnegative number. Value: `' + alpha + '`.' ); 59 } 60 if ( alpha < 0.0 || alpha > 1.0 ) { 61 throw new RangeError( 'invalid argument. Must provide a nonnegative number on the interval [0,1]. Value: `' + alpha + '`.' ); 62 } 63 c = 1.0 - alpha; 64 return accumulator; 65 66 /** 67 * If provided a value, the accumulator function returns an updated variance. If not provided a value, the accumulator function returns the current variance. 68 * 69 * @private 70 * @param {number} [x] - new value 71 * @returns {(number|null)} variance or null 72 */ 73 function accumulator( x ) { 74 if ( arguments.length === 0 ) { 75 return ( s2 === void 0 ) ? null : s2; 76 } 77 if ( s2 === void 0 ) { 78 m = x; 79 s2 = 0.0; 80 } else { 81 r = x - m; 82 incr = alpha * r; 83 m += incr; 84 s2 = c * ( s2+(r*incr) ); 85 } 86 return s2; 87 } 88 } 89 90 91 // EXPORTS // 92 93 module.exports = increwvariance;