time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

basic.js (2182B)


      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 = geometricSeriesClosure( 0.9 )
     46 * var out = sumSeries( gen );
     47 * // returns 10.0
     48 *
     49 * function geometricSeriesClosure( x ) {
     50 *     var exponent = -1;
     51 *     return function() {
     52 *         exponent += 1;
     53 *         return Math.pow( x, exponent );
     54 *     };
     55 * }
     56 */
     57 function sumSeries( generator, options ) {
     58 	var tolerance;
     59 	var nextTerm;
     60 	var counter;
     61 	var result;
     62 	var opts;
     63 
     64 	opts = {};
     65 
     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 	// Repeatedly call function...
     74 	do {
     75 		nextTerm = generator();
     76 		result += nextTerm;
     77 	}
     78 	while ( ( abs(tolerance * result) < abs(nextTerm) ) && --counter ); // eslint-disable-line no-plusplus
     79 
     80 	return result;
     81 }
     82 
     83 
     84 // EXPORTS //
     85 
     86 module.exports = sumSeries;