factory.js (2085B)
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 isnan = require( '@stdlib/math/base/assert/is-nan' ); 25 var floor = require( '@stdlib/math/base/special/floor' ); 26 var log1p = require( '@stdlib/math/base/special/log1p' ); 27 var pow = require( '@stdlib/math/base/special/pow' ); 28 var NINF = require( '@stdlib/constants/float64/ninf' ); 29 var PINF = require( '@stdlib/constants/float64/pinf' ); 30 31 32 // MAIN // 33 34 /** 35 * Returns a function for evaluating the logarithm of the cumulative distribution function (CDF) for a geometric distribution with success probability `p`. 36 * 37 * @param {Probability} p - success probability 38 * @returns {Function} logCDF 39 * 40 * @example 41 * var logcdf = factory( 0.5 ); 42 * var y = logcdf( 3.0 ); 43 * // returns ~-0.065 44 * 45 * y = logcdf( 1.0 ); 46 * // returns ~-0.288 47 */ 48 function factory( p ) { 49 if ( isnan( p ) || p < 0.0 || p > 1.0 ) { 50 return constantFunction( NaN ); 51 } 52 return logcdf; 53 54 /** 55 * Evaluates the logarithm of the cumulative distribution function (CDF) for a geometric distribution. 56 * 57 * @private 58 * @param {number} x - input value 59 * @returns {number} evaluated logCDF 60 * 61 * @example 62 * var y = logcdf( 2.0 ); 63 * // returns <number> 64 */ 65 function logcdf( x ) { 66 if ( isnan( x ) ) { 67 return NaN; 68 } 69 if ( x < 0.0 ) { 70 return NINF; 71 } 72 if ( x === PINF ) { 73 return 0.0; 74 } 75 x = floor( x ); 76 return log1p( -pow( 1.0 - p, x + 1.0 ) ); 77 } 78 } 79 80 81 // EXPORTS // 82 83 module.exports = factory;