factorial.js (1850B)
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 isnan = require( './../../../../base/assert/is-nan' ); 24 var isInteger = require( './../../../../base/assert/is-integer' ); 25 var gamma = require( './../../../../base/special/gamma' ); 26 var PINF = require( '@stdlib/constants/float64/pinf' ); 27 var FACTORIALS = require( './factorials.json' ); 28 29 30 // VARIABLES // 31 32 var MAX_FACTORIAL = 170; // TODO: consider extracting as a constant 33 34 35 // MAIN // 36 37 /** 38 * Evaluates the factorial of `x`. 39 * 40 * @param {number} x - input value 41 * @returns {number} factorial 42 * 43 * @example 44 * var v = factorial( 3.0 ); 45 * // returns 6.0 46 * 47 * @example 48 * var v = factorial( -1.5 ); 49 * // returns ~-3.545 50 * 51 * @example 52 * var v = factorial( -0.5 ); 53 * // returns ~1.772 54 * 55 * @example 56 * var v = factorial( 0.5 ); 57 * // returns ~0.886 58 * 59 * @example 60 * var v = factorial( -10.0 ); 61 * // returns NaN 62 * 63 * @example 64 * var v = factorial( 171.0 ); 65 * // returns Infinity 66 * 67 * @example 68 * var v = factorial( NaN ); 69 * // returns NaN 70 */ 71 function factorial( x ) { 72 if ( isnan( x ) ) { 73 return NaN; 74 } 75 if ( isInteger( x ) ) { 76 if ( x < 0 ) { 77 return NaN; 78 } 79 if ( x <= MAX_FACTORIAL ) { 80 return FACTORIALS[ x ]; 81 } 82 return PINF; 83 } 84 return gamma( x + 1.0 ); 85 } 86 87 88 // EXPORTS // 89 90 module.exports = factorial;