time-to-botec

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

stirling_approximation.js (2170B)


      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 * ## Notice
     20 *
     21 * The original C code, copyright, license, and constants are from [Cephes]{@link http://www.netlib.org/cephes}. The implementation follows the original, but has been modified for JavaScript.
     22 *
     23 * ```text
     24 * Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
     25 *
     26 * Some software in this archive may be from the book _Methods and Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster International, 1989) or from the Cephes Mathematical Library, a commercial product. In either event, it is copyrighted by the author. What you see here may be used freely but it comes with no support or guarantee.
     27 *
     28 * Stephen L. Moshier
     29 * moshier@na-net.ornl.gov
     30 * ```
     31 */
     32 
     33 'use strict';
     34 
     35 // MODULES //
     36 
     37 var SQRT_TWO_PI = require( '@stdlib/constants/float64/sqrt-two-pi' );
     38 var pow = require( './../../../../base/special/pow' );
     39 var exp = require( './../../../../base/special/exp' );
     40 var polyval = require( './polyval_s.js' );
     41 
     42 
     43 // VARIABLES //
     44 
     45 var MAX_STIRLING = 143.01608;
     46 
     47 
     48 // MAIN //
     49 
     50 /**
     51 * Evaluates the gamma function using Stirling's formula. The polynomial is valid for \\(33 \leq x \leq 172\\).
     52 *
     53 * @private
     54 * @param {number} x - input value
     55 * @returns {number} function value
     56 */
     57 function gamma( x ) {
     58 	var w;
     59 	var y;
     60 	var v;
     61 
     62 	w = 1.0 / x;
     63 	w = 1.0 + ( w * polyval( w ) );
     64 	y = exp( x );
     65 
     66 	// Check `x` to avoid `pow()` overflow...
     67 	if ( x > MAX_STIRLING ) {
     68 		v = pow( x, ( 0.5*x ) - 0.25 );
     69 		y = v * (v/y);
     70 	} else {
     71 		y = pow( x, x-0.5 ) / y;
     72 	}
     73 	return SQRT_TWO_PI * y * w;
     74 }
     75 
     76 
     77 // EXPORTS //
     78 
     79 module.exports = gamma;