main.js (2097B)
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 /** 22 * Returns an accumulator function which incrementally computes an arithmetic mean. 23 * 24 * ## Method 25 * 26 * - This implementation uses [Welford's method][algorithms-variance] for efficient computation, which can be derived as follows 27 * 28 * ```tex 29 * \begin{align*} 30 * \mu_n &= \frac{1}{n} \sum_{i=0}^{n-1} x_i \\ 31 * &= \frac{1}{n} \biggl(x_{n-1} + \sum_{i=0}^{n-2} x_i \biggr) \\ 32 * &= \frac{1}{n} (x_{n-1} + (n-1)\mu_{n-1}) \\ 33 * &= \mu_{n-1} + \frac{1}{n} (x_{n-1} - \mu_{n-1}) 34 * \end{align*} 35 * ``` 36 * 37 * [algorithms-variance]: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance 38 * 39 * @returns {Function} accumulator function 40 * 41 * @example 42 * var accumulator = incrmean(); 43 * 44 * var mu = accumulator(); 45 * // returns null 46 * 47 * mu = accumulator( 2.0 ); 48 * // returns 2.0 49 * 50 * mu = accumulator( -5.0 ); 51 * // returns -1.5 52 * 53 * mu = accumulator(); 54 * // returns -1.5 55 */ 56 function incrmean() { 57 var mu; 58 var N; 59 60 mu = 0.0; 61 N = 0; 62 63 return accumulator; 64 65 /** 66 * If provided a value, the accumulator function returns an updated mean. If not provided a value, the accumulator function returns the current mean. 67 * 68 * @private 69 * @param {number} [x] - new value 70 * @returns {(number|null)} mean value or null 71 */ 72 function accumulator( x ) { 73 if ( arguments.length === 0 ) { 74 if ( N === 0 ) { 75 return null; 76 } 77 return mu; 78 } 79 N += 1; 80 mu += (x-mu) / N; 81 return mu; 82 } 83 } 84 85 86 // EXPORTS // 87 88 module.exports = incrmean;