factory.js (2524B)
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 binomcoefln = require( '@stdlib/math/base/special/binomcoefln' ); 26 var degenerate = require( './../../../../../base/dists/degenerate/pmf' ).factory; 27 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 28 var log1p = require( '@stdlib/math/base/special/log1p' ); 29 var exp = require( '@stdlib/math/base/special/exp' ); 30 var ln = require( '@stdlib/math/base/special/ln' ); 31 var PINF = require( '@stdlib/constants/float64/pinf' ); 32 33 34 // MAIN // 35 36 /** 37 * Returns a function for evaluating the probability mass function (PMF) for a binomial distribution with number of trials `n` and success probability `p`. 38 * 39 * @param {NonNegativeInteger} n - number of trials 40 * @param {Probability} p - success probability 41 * @returns {Function} PMF 42 * 43 * @example 44 * var pmf = factory( 10, 0.5 ); 45 * var y = pmf( 3.0 ); 46 * // returns ~0.117 47 * 48 * y = pmf( 5.0 ); 49 * // returns ~0.246 50 */ 51 function factory( n, p ) { 52 if ( 53 isnan( n ) || 54 isnan( p ) || 55 !isNonNegativeInteger( n ) || 56 n === PINF || 57 p < 0.0 || 58 p > 1.0 59 ) { 60 return constantFunction( NaN ); 61 } 62 if ( p === 0.0 || n === 0 ) { 63 return degenerate( 0.0 ); 64 } 65 if ( p === 1.0 ) { 66 return degenerate( n ); 67 } 68 return pmf; 69 70 /** 71 * Evaluates the probability mass function (PMF) for a binomial distribution. 72 * 73 * @private 74 * @param {number} x - input value 75 * @returns {Probability} evaluated PMF 76 * 77 * @example 78 * var y = pmf( 2.0 ); 79 * // returns <number> 80 */ 81 function pmf( x ) { 82 var lnl; 83 if ( isnan( x ) ) { 84 return NaN; 85 } 86 if ( isNonNegativeInteger( x ) ) { 87 if ( x > n ) { 88 return 0.0; 89 } 90 lnl = binomcoefln( n, x ); 91 lnl += (x * ln( p )) + ((n - x) * log1p( -p )); 92 return exp( lnl ); 93 } 94 return 0.0; 95 } 96 } 97 98 99 // EXPORTS // 100 101 module.exports = factory;