cdf.js (2485B)
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 betainc = require( '@stdlib/math/base/special/betainc' ); 24 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 25 var floor = require( '@stdlib/math/base/special/floor' ); 26 var PINF = require( '@stdlib/constants/float64/pinf' ); 27 28 29 // MAIN // 30 31 /** 32 * Evaluates the cumulative distribution function (CDF) for a negative binomial distribution with number of successes until experiment is stopped `r` and success probability `p` at a value `x`. 33 * 34 * @param {number} x - input value 35 * @param {PositiveNumber} r - number of successes until experiment is stopped 36 * @param {Probability} p - success probability 37 * @returns {Probability} evaluated CDF 38 * 39 * @example 40 * var y = cdf( 5.0, 20.0, 0.8 ); 41 * // returns ~0.617 42 * 43 * @example 44 * var y = cdf( 21.0, 20.0, 0.5 ); 45 * // returns ~0.622 46 * 47 * @example 48 * var y = cdf( 5.0, 10.0, 0.4 ); 49 * // returns ~0.034 50 * 51 * @example 52 * var y = cdf( 0.0, 10.0, 0.9 ); 53 * // returns ~0.349 54 * 55 * @example 56 * var y = cdf( 21.0, 15.5, 0.5 ); 57 * // returns ~0.859 58 * 59 * @example 60 * var y = cdf( 5.0, 7.4, 0.4 ); 61 * // returns ~0.131 62 * 63 * @example 64 * var y = cdf( 2.0, 0.0, 0.5 ); 65 * // returns NaN 66 * 67 * @example 68 * var y = cdf( 2.0, -2.0, 0.5 ); 69 * // returns NaN 70 * 71 * @example 72 * var y = cdf( NaN, 20.0, 0.5 ); 73 * // returns NaN 74 * 75 * @example 76 * var y = cdf( 0.0, NaN, 0.5 ); 77 * // returns NaN 78 * 79 * @example 80 * var y = cdf( 0.0, 20.0, NaN ); 81 * // returns NaN 82 * 83 * @example 84 * var y = cdf( 2.0, 20, -1.0 ); 85 * // returns NaN 86 * 87 * @example 88 * var y = cdf( 2.0, 20, 1.5 ); 89 * // returns NaN 90 */ 91 function cdf( x, r, p ) { 92 var xint; 93 if ( 94 isnan( x ) || 95 isnan( r ) || 96 isnan( p ) || 97 r <= 0.0 || 98 p < 0.0 || 99 p > 1.0 100 ) { 101 return NaN; 102 } 103 if ( x < 0.0 ) { 104 return 0.0; 105 } 106 if ( x === PINF ) { 107 return 1.0; 108 } 109 // Ensure left-continuity: 110 xint = floor( x + 1e-7 ); 111 return betainc( p, r, xint + 1.0 ); 112 } 113 114 115 // EXPORTS // 116 117 module.exports = cdf;