time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

factory.js (1978B)


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