quantile.js (2451B)
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 isnan = require( '@stdlib/math/base/assert/is-nan' ); 24 var sqrt = require( '@stdlib/math/base/special/sqrt' ); 25 26 27 // MAIN // 28 29 /** 30 * Evaluates the quantile function for a triangular distribution with lower limit `a` and upper limit `b` and mode `c` at a probability `p`. 31 * 32 * @param {Probability} p - input value 33 * @param {number} a - lower limit 34 * @param {number} b - upper limit 35 * @param {number} c - mode 36 * @returns {number} evaluated quantile function 37 * 38 * @example 39 * var y = quantile( 0.9, -1.0, 1.0, 0.0 ); 40 * // returns ~0.553 41 * 42 * @example 43 * var y = quantile( 0.1, -1.0, 1.0, 0.5 ); 44 * // returns ~-0.452 45 * 46 * @example 47 * var y = quantile( 0.1, -20.0, 0.0, -2.0 ); 48 * // returns -14.0 49 * 50 * @example 51 * var y = quantile( 0.8, 0.0, 20.0, 0.0 ); 52 * // returns ~11.056 53 * 54 * @example 55 * var y = quantile( 1.1, -1.0, 1.0, 0.0 ); 56 * // returns NaN 57 * 58 * @example 59 * var y = quantile( -0.1, -1.0, 1.0, 0.0 ); 60 * // returns NaN 61 * 62 * @example 63 * var y = quantile( NaN, 0.0, 1.0, 0.5 ); 64 * // returns NaN 65 * 66 * @example 67 * var y = quantile( 0.3, NaN, 1.0, 0.5 ); 68 * // returns NaN 69 * 70 * @example 71 * var y = quantile( 0.3, 0.0, NaN, 0.5 ); 72 * // returns NaN 73 * 74 * @example 75 * var y = quantile( 0.3, 1.0, 0.0, NaN ); 76 * // returns NaN 77 * 78 * @example 79 * var y = quantile( 0.3, 1.0, 0.0, 1.5 ); 80 * // returns NaN 81 */ 82 function quantile( p, a, b, c ) { 83 var pInflection; 84 var fact1; 85 var fact2; 86 87 if ( 88 isnan( p ) || 89 isnan( a ) || 90 isnan( b ) || 91 isnan( c ) || 92 a > c || 93 c > b || 94 p < 0.0 || 95 p > 1.0 96 ) { 97 return NaN; 98 } 99 pInflection = ( c - a ) / ( b - a ); 100 fact1 = ( b - a ) * ( c - a); 101 fact2 = ( b - a ) * ( b - c ); 102 if ( p < pInflection ) { 103 return a + sqrt( fact1 * p ); 104 } 105 if ( p > pInflection ) { 106 return b - sqrt( fact2 * ( 1.0 - p ) ); 107 } 108 // Case: p = pInflection 109 return c; 110 } 111 112 113 // EXPORTS // 114 115 module.exports = quantile;