pmf.js (2034B)
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 factorialln = require( '@stdlib/math/base/special/factorialln' ); 25 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 26 var exp = require( '@stdlib/math/base/special/exp' ); 27 var ln = require( '@stdlib/math/base/special/ln' ); 28 var PINF = require( '@stdlib/constants/float64/pinf' ); 29 30 31 // MAIN // 32 33 /** 34 * Evaluates the probability mass function (PMF) for a Poisson distribution with mean parameter `lambda` at a value `x`. 35 * 36 * @param {number} x - input value 37 * @param {NonNegativeNumber} lambda - mean parameter 38 * @returns {Probability} evaluated PMF 39 * 40 * @example 41 * var y = pmf( 4.0, 3.0 ); 42 * // returns ~0.168 43 * 44 * @example 45 * var y = pmf( 1.0, 3.0 ); 46 * // returns ~0.149 47 * 48 * @example 49 * var y = pmf( -1.0, 2.0 ); 50 * // returns 0.0 51 * 52 * @example 53 * var y = pmf( 0.0, NaN ); 54 * // returns NaN 55 * 56 * @example 57 * var y = pmf( NaN, 0.5 ); 58 * // returns NaN 59 * 60 * @example 61 * // Invalid mean parameter: 62 * var y = pmf( 2.0, -0.5 ); 63 * // returns NaN 64 */ 65 function pmf( x, lambda ) { 66 var lnl; 67 if ( isnan( x ) || isnan( lambda ) || lambda < 0.0 ) { 68 return NaN; 69 } 70 if ( lambda === 0.0 ) { 71 return ( x === 0.0 ) ? 1.0 : 0.0; 72 } 73 if ( isNonNegativeInteger( x ) && x !== PINF ) { 74 lnl = (x * ln( lambda )) - lambda - factorialln( x ); 75 return exp( lnl ); 76 } 77 return 0.0; 78 } 79 80 81 // EXPORTS // 82 83 module.exports = pmf;