quantile.js (2633B)
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 erfcinv = require( '@stdlib/math/base/special/erfcinv' ); 24 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 25 var round = require( '@stdlib/math/base/special/round' ); 26 var sqrt = require( '@stdlib/math/base/special/sqrt' ); 27 var cdf = require( './../../../../../base/dists/poisson/cdf' ); 28 var SQRT2 = require( '@stdlib/constants/float64/sqrt-two' ); 29 var PINF = require( '@stdlib/constants/float64/pinf' ); 30 var search = require( './search.js' ); 31 32 33 // MAIN // 34 35 /** 36 * Evaluates the quantile function for a Poisson distribution with mean parameter `lambda` at a probability `p`. 37 * 38 * @param {Probability} p - input value 39 * @param {NonNegativeNumber} lambda - mean parameter 40 * @returns {NonNegativeInteger} evaluated quantile function 41 * 42 * @example 43 * var y = quantile( 0.5, 2.0 ); 44 * // returns 2 45 * 46 * @example 47 * var y = quantile( 0.9, 4.0 ); 48 * // returns 7 49 * 50 * @example 51 * var y = quantile( 0.1, 200.0 ); 52 * // returns 182 53 * 54 * @example 55 * var y = quantile( 1.1, 0.0 ); 56 * // returns NaN 57 * 58 * @example 59 * var y = quantile( -0.2, 0.0 ); 60 * // returns NaN 61 * 62 * @example 63 * var y = quantile( NaN, 0.5 ); 64 * // returns NaN 65 * 66 * @example 67 * var y = quantile( 0.0, NaN ); 68 * // returns NaN 69 */ 70 function quantile( p, lambda ) { 71 var sigmaInv; 72 var guess; 73 var sigma; 74 var corr; 75 var x2; 76 var x; 77 if ( isnan( lambda ) || lambda < 0.0 ) { 78 return NaN; 79 } 80 if ( isnan( p ) || p < 0.0 || p > 1.0 ) { 81 return NaN; 82 } 83 if ( lambda === 0.0 ) { 84 return 0.0; 85 } 86 if ( p === 0.0 ) { 87 return 0.0; 88 } 89 if ( p === 1.0 ) { 90 return PINF; 91 } 92 // Cornish-Fisher expansion: 93 sigma = sqrt( lambda ); 94 sigmaInv = 1.0 / sigma; 95 if ( p < 0.5 ) { 96 x = -erfcinv( 2.0 * p ) * SQRT2; 97 } else { 98 x = erfcinv( 2.0 * ( 1.0 - p ) ) * SQRT2; 99 } 100 x2 = x * x; 101 102 // Skewness correction: 103 corr = x + (sigmaInv * ( x2 - 1.0 ) / 6.0); 104 guess = round( lambda + (sigma * corr) ); 105 return ( cdf( guess, lambda ) >= p ) ? 106 search.left( guess, p, lambda ) : 107 search.right( guess, p, lambda ); 108 } 109 110 111 // EXPORTS // 112 113 module.exports = quantile;