generators.js (2582B)
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 abs = require( './../../../../base/special/abs' ); 24 var EPS = require( '@stdlib/constants/float64/eps' ); 25 26 27 // VARIABLES // 28 29 var MAX_TERMS = 1000000; 30 31 32 // MAIN // 33 34 /** 35 * Sum the elements of the series given by the supplied function. 36 * 37 * @param {Function} generator - series function 38 * @param {Object} [options] - function options 39 * @param {PositiveInteger} [options.maxTerms=1000000] - maximum number of terms to be added 40 * @param {PositiveNumber} [options.tolerance=2.22e-16] - further terms are only added as long as the next term is greater than current term times the tolerance 41 * @param {number} [options.initialValue=0] - initial value of the resulting sum 42 * @returns {number} sum of all series terms 43 * 44 * @example 45 * var gen = geometricSeriesGenerator( 0.9 ); 46 * var out = sumSeries( gen ); 47 * // returns 10.0 48 * 49 * function* geometricSeriesGenerator( x ) { 50 * var exponent = 0; 51 * while ( true ) { 52 * yield Math.pow( x, exponent ); 53 * exponent += 1; 54 * } 55 * } 56 */ 57 function sumSeries( generator, options ) { 58 var isgenerator; 59 var tolerance; 60 var nextTerm; 61 var counter; 62 var result; 63 var opts; 64 65 opts = {}; 66 if ( arguments.length > 1 ) { 67 opts = options; 68 } 69 tolerance = opts.tolerance || EPS; 70 counter = opts.maxTerms || MAX_TERMS; 71 result = opts.initialValue || 0; 72 73 isgenerator = typeof generator.next === 'function'; 74 if ( isgenerator === true ) { 75 // Case A: Iterate over generator object created by a generator function... 76 for ( nextTerm of generator ) { 77 result += nextTerm; 78 if ( 79 abs(tolerance * result) >= abs(nextTerm) || 80 --counter === 0 // eslint-disable-line no-plusplus 81 ) { 82 break; 83 } 84 } 85 } else { 86 // Case B: Repeatedly call function... 87 do { 88 nextTerm = generator(); 89 result += nextTerm; 90 } 91 while ( ( abs(tolerance * result) < abs(nextTerm) ) && --counter ); // eslint-disable-line no-plusplus 92 } 93 return result; 94 } 95 96 97 // EXPORTS // 98 99 module.exports = sumSeries;