cdf.js (2363B)
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 betainc = require( '@stdlib/math/base/special/betainc' ); 25 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 26 var floor = require( '@stdlib/math/base/special/floor' ); 27 var PINF = require( '@stdlib/constants/float64/pinf' ); 28 29 30 // MAIN // 31 32 /** 33 * Evaluates the cumulative distribution function (CDF) for a binomial distribution with number of trials `n` and success probability `p` at a value `x`. 34 * 35 * @param {number} x - input value 36 * @param {NonNegativeInteger} n - number of trials 37 * @param {Probability} p - success probability 38 * @returns {Probability} evaluated CDF 39 * 40 * @example 41 * var y = cdf( 3.0, 20, 0.2 ); 42 * // returns ~0.411 43 * 44 * @example 45 * var y = cdf( 21.0, 20, 0.2 ); 46 * // returns 1.0 47 * 48 * @example 49 * var y = cdf( 5.0, 10, 0.4 ); 50 * // returns ~0.834 51 * 52 * @example 53 * var y = cdf( 0.0, 10, 0.4 ); 54 * // returns ~0.006 55 * 56 * @example 57 * var y = cdf( NaN, 20, 0.5 ); 58 * // returns NaN 59 * 60 * @example 61 * var y = cdf( 0.0, NaN, 0.5 ); 62 * // returns NaN 63 * 64 * @example 65 * var y = cdf( 0.0, 20, NaN ); 66 * // returns NaN 67 * 68 * @example 69 * var y = cdf( 2.0, 1.5, 0.5 ); 70 * // returns NaN 71 * 72 * @example 73 * var y = cdf( 2.0, -2.0, 0.5 ); 74 * // returns NaN 75 * 76 * @example 77 * var y = cdf( 2.0, 20, -1.0 ); 78 * // returns NaN 79 * 80 * @example 81 * var y = cdf( 2.0, 20, 1.5 ); 82 * // returns NaN 83 */ 84 function cdf( x, n, p ) { 85 if ( 86 isnan( x ) || 87 isnan( n ) || 88 isnan( p ) || 89 p < 0.0 || 90 p > 1.0 || 91 !isNonNegativeInteger( n ) || 92 n === PINF 93 ) { 94 return NaN; 95 } 96 if ( x < 0.0 ) { 97 return 0.0; 98 } 99 if ( x >= n ) { 100 return 1.0; 101 } 102 x = floor( x + 1.0e-7 ); 103 return betainc( p, x + 1.0, n - x, true, true ); 104 } 105 106 107 // EXPORTS // 108 109 module.exports = cdf;