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