main.js (2232B)
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 incrmean = require( './../../../incr/mean' ); 24 25 26 // MAIN // 27 28 /** 29 * Returns an accumulator function which incrementally computes a harmonic mean. 30 * 31 * ## Method 32 * 33 * - The harmonic mean of positive real numbers \\(x_0, x_1, \ldots, x_{n-1}\\) is defined as 34 * 35 * ```tex 36 * \begin{align*} 37 * H &= \frac{n}{\frac{1}{x_0} + \frac{1}{x_1} + \cdots + \frac{1}{x_{n-1}}} \\ 38 * &= \frac{n}{\sum_{i=0}^{n-1} \frac{1}{x_i}} 39 * \end{align*} 40 * ``` 41 * 42 * which may be expressed 43 * 44 * ```tex 45 * H = \biggl( \frac{\sum_{i=0}^{n-1} \frac{1}{x_i}}{n} \biggr)^{-1} 46 * ``` 47 * 48 * - Accordingly, to compute the harmonic mean incrementally, we can simply compute the arithmetic mean of reciprocal values and then compute the reciprocal of the result. 49 * 50 * @returns {Function} accumulator function 51 * 52 * @example 53 * var accumulator = incrhmean(); 54 * 55 * var v = accumulator(); 56 * // returns null 57 * 58 * v = accumulator( 2.0 ); 59 * // returns 2.0 60 * 61 * v = accumulator( 5.0 ); 62 * // returns ~2.86 63 * 64 * v = accumulator(); 65 * // returns ~2.86 66 */ 67 function incrhmean() { 68 var mean = incrmean(); 69 var v; 70 return accumulator; 71 72 /** 73 * If provided a value, the accumulator function returns an updated harmonic mean. If not provided a value, the accumulator function returns the current harmonic mean. 74 * 75 * @private 76 * @param {number} [x] - new value 77 * @returns {(number|null)} harmonic mean or null 78 */ 79 function accumulator( x ) { 80 if ( arguments.length === 0 ) { 81 return ( v === void 0 ) ? null : v; 82 } 83 v = 1.0 / mean( 1.0/x ); 84 return v; 85 } 86 } 87 88 89 // EXPORTS // 90 91 module.exports = incrhmean;