main.js (1739B)
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 ln = require( '@stdlib/math/base/special/ln' ); 24 var exp = require( '@stdlib/math/base/special/exp' ); 25 26 27 // MAIN // 28 29 /** 30 * Returns an accumulator function which incrementally computes a geometric mean. 31 * 32 * @returns {Function} accumulator function 33 * 34 * @example 35 * var accumulator = incrgmean(); 36 * 37 * var v = accumulator(); 38 * // returns null 39 * 40 * v = accumulator( 2.0 ); 41 * // returns 2.0 42 * 43 * v = accumulator( 5.0 ); 44 * // returns ~3.16 45 * 46 * v = accumulator(); 47 * // returns ~3.16 48 */ 49 function incrgmean() { 50 var sum; 51 var N; 52 var v; 53 54 sum = 0.0; 55 N = 0; 56 v = 1; 57 58 return accumulator; 59 60 /** 61 * If provided a value, the accumulator function returns an updated geometric mean. If not provided a value, the accumulator function returns the current geometric mean. 62 * 63 * @private 64 * @param {number} [x] - new value 65 * @returns {(number|null)} geometric mean or null 66 */ 67 function accumulator( x ) { 68 if ( arguments.length === 0 ) { 69 if ( N === 0 ) { 70 return null; 71 } 72 return v; 73 } 74 N += 1; 75 sum += ln( x ); 76 v = exp( sum/N ); 77 return v; 78 } 79 } 80 81 82 // EXPORTS // 83 84 module.exports = incrgmean;