factory.js (2244B)
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 isNonNegativeInteger = require( '@stdlib/math/base/assert/is-nonnegative-integer' ); 24 var constantFunction = require( '@stdlib/utils/constant-function' ); 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 ibetaDerivative = require( './ibeta_derivative.js' ); 29 30 31 // MAIN // 32 33 /** 34 * Returns a function for evaluating the natural logarithm of the probability mass function (PMF) for a negative binomial distribution with number of successes until experiment is stopped `r` and success probability `p`. 35 * 36 * @param {PositiveNumber} r - number of successes until experiment is stopped 37 * @param {Probability} p - success probability 38 * @returns {Function} logPMF 39 * 40 * @example 41 * var logpmf = factory( 10, 0.5 ); 42 * var y = logpmf( 3.0 ); 43 * // returns ~-3.617 44 * 45 * y = logpmf( 5.0 ); 46 * // returns ~-2.795 47 */ 48 function factory( r, p ) { 49 if ( 50 isnan( r ) || 51 isnan( p ) || 52 r <= 0.0 || 53 p <= 0.0 || 54 p > 1.0 55 ) { 56 return constantFunction( NaN ); 57 } 58 return logpmf; 59 60 /** 61 * Evaluates the natural logarithm of the probability mass function (PMF) for a negative binomial distribution. 62 * 63 * @private 64 * @param {number} x - input value 65 * @returns {number} evaluated logPMF 66 * 67 * @example 68 * var y = logpmf( 2.0 ); 69 * // returns <number> 70 */ 71 function logpmf( x ) { 72 if ( isnan( x ) ) { 73 return NaN; 74 } 75 if ( !isNonNegativeInteger( x ) ) { 76 return NINF; 77 } 78 return ln( p ) - ln( r + x ) + ln( ibetaDerivative( p, r, x + 1.0 ) ); 79 } 80 } 81 82 83 // EXPORTS // 84 85 module.exports = factory;