factory.js (2252B)
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 constantFunction = require( '@stdlib/utils/constant-function' ); 24 var degenerate = require( './../../../../../base/dists/degenerate/logpdf' ).factory; 25 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 26 var ln = require( '@stdlib/math/base/special/ln' ); 27 var NINF = require( '@stdlib/constants/float64/ninf' ); 28 var PINF = require( '@stdlib/constants/float64/pinf' ); 29 var gammaDeriv = require( './gamma_p_derivative.js' ); 30 31 32 // MAIN // 33 34 /** 35 * Returns a function for evaluating the logarithm of the probability density function (PDF) for a gamma distribution with shape parameter `alpha` and rate parameter `beta`. 36 * 37 * @param {NonNegativeNumber} alpha - shape parameter 38 * @param {PositiveNumber} beta - rate parameter 39 * @returns {Function} logPDF 40 * 41 * @example 42 * var logpdf = factory( 3.0, 1.5 ); 43 * 44 * var y = logpdf( 1.0 ); 45 * // returns ~-0.977 46 * 47 * y = logpdf( 4.0 ); 48 * // returns ~-2.704 49 */ 50 function factory( alpha, beta ) { 51 if ( 52 isnan( alpha ) || 53 isnan( beta ) || 54 alpha < 0.0 || 55 beta <= 0.0 56 ) { 57 return constantFunction( NaN ); 58 } 59 if ( alpha === 0.0 ) { 60 return degenerate( 0.0 ); 61 } 62 return logpdf; 63 64 /** 65 * Evaluates the logarithm of the probability density function (PDF) for a gamma distribution. 66 * 67 * @private 68 * @param {number} x - input value 69 * @returns {number} evaluated logPDF 70 * 71 * @example 72 * var y = logpdf( -1.2 ); 73 * // returns <number> 74 */ 75 function logpdf( x ) { 76 if ( isnan( x ) ) { 77 return NaN; 78 } 79 if ( x < 0.0 || x === PINF ) { 80 return NINF; 81 } 82 return ln( gammaDeriv( alpha, x * beta ) ) + ln( beta ); 83 } 84 } 85 86 87 // EXPORTS // 88 89 module.exports = factory;