time-to-botec

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

stirling.js (2096B)


      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 gammaln = require( './../../../../base/special/gammaln' );
     24 var ln = require( './../../../../base/special/ln' );
     25 var LN_SQRT_TWO_PI = require( '@stdlib/constants/float64/ln-sqrt-two-pi' );
     26 var SMALLEST_FLOAT32 = require( '@stdlib/constants/float32/smallest-normal' );
     27 var MAX_FLOAT32 = require( '@stdlib/constants/float32/max' );
     28 var chepolsum = require( './chepolsum.js' );
     29 var polyvalC = require( './polyval_c.js' );
     30 var polyvalD = require( './polyval_d.js' );
     31 
     32 
     33 // VARIABLES //
     34 
     35 var C6 = 0.30865217988013567769;
     36 
     37 
     38 // MAIN //
     39 
     40 /**
     41 * Computes the Stirling series corresponding to asymptotic series for the logarithm of the gamma function.
     42 *
     43 * ```tex
     44 * \frac{1}{12x}-\frac{1}{360x^3}\ldots; x \ge 3
     45 * ```
     46 *
     47 * @private
     48 * @param {number} x - input value
     49 * @returns {number} function value
     50 */
     51 function stirling( x ) {
     52 	var z;
     53 	if ( x < SMALLEST_FLOAT32 ) {
     54 		return MAX_FLOAT32;
     55 	}
     56 	if ( x < 1.0 ) {
     57 		return gammaln( x+1.0 ) - ( (x+0.5) * ln(x) ) + x - LN_SQRT_TWO_PI;
     58 	}
     59 	if ( x < 2.0 ) {
     60 		return gammaln( x ) - ( (x-0.5) * ln(x) ) + x - LN_SQRT_TWO_PI;
     61 	}
     62 	if ( x < 3.0 ) {
     63 		return gammaln( x-1.0 ) - ( (x-0.5) * ln(x) ) + x - LN_SQRT_TWO_PI + ln( x-1.0 ); // eslint-disable-line max-len
     64 	}
     65 	if ( x < 12.0 ) {
     66 		z = ( 18.0/( x*x ) ) - 1.0;
     67 		return chepolsum( 17, z ) / ( 12.0*x );
     68 	}
     69 	z = 1.0 / ( x * x );
     70 	if ( x < 1000.0 ) {
     71 		return polyvalC( z ) / ( C6+z ) / x;
     72 	}
     73 	return polyvalD( z ) / x;
     74 }
     75 
     76 
     77 // EXPORTS //
     78 
     79 module.exports = stirling;