main.js (2724B)
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 isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; 24 var incrmmean = require( './../../../incr/mmean' ); 25 26 27 // MAIN // 28 29 /** 30 * Returns an accumulator function which incrementally computes a moving harmonic mean. 31 * 32 * ## Method 33 * 34 * - The harmonic mean of positive real numbers \\(x_0, x_1, \ldots, x_{n-1}\\) is defined as 35 * 36 * ```tex 37 * \begin{align*} 38 * H &= \frac{n}{\frac{1}{x_0} + \frac{1}{x_1} + \cdots + \frac{1}{x_{n-1}}} \\ 39 * &= \frac{n}{\sum_{i=0}^{n-1} \frac{1}{x_i}} 40 * \end{align*} 41 * ``` 42 * 43 * which may be expressed 44 * 45 * ```tex 46 * H = \biggl( \frac{\sum_{i=0}^{n-1} \frac{1}{x_i}}{n} \biggr)^{-1} 47 * ``` 48 * 49 * - Accordingly, to compute the harmonic mean for each window incrementally, we can simply compute the arithmetic mean of reciprocal values and then compute the reciprocal of the result. 50 * 51 * @param {PositiveInteger} W - window size 52 * @throws {TypeError} must provide a positive integer 53 * @returns {Function} accumulator function 54 * 55 * @example 56 * var accumulator = incrmhmean( 3 ); 57 * 58 * var v = accumulator(); 59 * // returns null 60 * 61 * v = accumulator( 2.0 ); 62 * // returns 2.0 63 * 64 * v = accumulator( 5.0 ); 65 * // returns ~2.86 66 * 67 * v = accumulator( 3.0 ); 68 * // returns ~2.90 69 * 70 * v = accumulator( 5.0 ); 71 * // returns ~4.09 72 * 73 * v = accumulator(); 74 * // returns ~4.09 75 */ 76 function incrmhmean( W ) { 77 var mmean; 78 if ( !isPositiveInteger( W ) ) { 79 throw new TypeError( 'invalid argument. Must provide a positive integer. Value: `' + W + '`.' ); 80 } 81 mmean = incrmmean( W ); 82 return accumulator; 83 84 /** 85 * 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. 86 * 87 * @private 88 * @param {number} [x] - input value 89 * @returns {(number|null)} harmonic mean or null 90 */ 91 function accumulator( x ) { 92 var v; 93 if ( arguments.length === 0 ) { 94 v = mmean(); 95 if ( v === null ) { 96 return v; 97 } 98 return 1.0 / v; 99 } 100 return 1.0 / mmean( 1.0/x ); 101 } 102 } 103 104 105 // EXPORTS // 106 107 module.exports = incrmhmean;