factory.js (2205B)
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 betainc = require( '@stdlib/math/base/special/betainc' ); 26 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 27 var floor = require( '@stdlib/math/base/special/floor' ); 28 var PINF = require( '@stdlib/constants/float64/pinf' ); 29 30 31 // MAIN // 32 33 /** 34 * Returns a function for evaluating the cumulative distribution function (CDF) for a binomial distribution with number of trials `n` and success probability `p`. 35 * 36 * @param {NonNegativeInteger} n - number of trials 37 * @param {Probability} p - success probability 38 * @returns {Function} CDF 39 * 40 * @example 41 * var cdf = factory( 10, 0.5 ); 42 * var y = cdf( 3.0 ); 43 * // returns ~0.172 44 * 45 * y = cdf( 1.0 ); 46 * // returns ~0.011 47 */ 48 function factory( n, p ) { 49 if ( 50 isnan( n ) || 51 isnan( p ) || 52 p < 0.0 || 53 p > 1.0 || 54 !isNonNegativeInteger( n ) || 55 n === PINF 56 ) { 57 return constantFunction( NaN ); 58 } 59 return cdf; 60 61 /** 62 * Evaluates the cumulative distribution function (CDF) for a binomial distribution. 63 * 64 * @private 65 * @param {number} x - input value 66 * @returns {Probability} evaluated CDF 67 * 68 * @example 69 * var y = cdf( 2.0 ); 70 * // returns <number> 71 */ 72 function cdf( x ) { 73 if ( isnan( x ) ) { 74 return NaN; 75 } 76 if ( x < 0.0 ) { 77 return 0.0; 78 } 79 if ( x >= n ) { 80 return 1.0; 81 } 82 // Ensure left-continuity: 83 x = floor( x + 1.0e-7 ); 84 return betainc( p, x + 1.0, n - x, true, true ); 85 } 86 } 87 88 89 // EXPORTS // 90 91 module.exports = factory;