bisect.js (1453B)
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 cosineCDF = require( './../../../../../base/dists/cosine/cdf' ); 24 25 26 // VARIABLES // 27 28 var MAX_ITERATIONS = 1e4; 29 var TOLERANCE = 1e-12; 30 31 32 // MAIN // 33 34 /** 35 * Bisection method to find quantile as there is no closed-form expression for the inverse of the CDF. 36 * 37 * @private 38 * @param {Probability} p - input value 39 * @param {number} mu - location parameter 40 * @param {NonNegativeNumber} s - scale parameter 41 * @returns {number} evaluated quantile function 42 */ 43 function bisect( p, mu, s ) { 44 var a; 45 var b; 46 var c; 47 var m; 48 var n; 49 50 n = 1; 51 a = mu - s; 52 b = mu + s; 53 while ( n < MAX_ITERATIONS ) { 54 m = ( a + b ) / 2.0; 55 if ( b - a < TOLERANCE ) { 56 return m; 57 } 58 c = cosineCDF( m, mu, s); 59 if ( p > c ) { 60 a = m; 61 } else { 62 b = m; 63 } 64 n += 1; 65 } 66 return m; 67 } 68 69 70 // EXPORTS // 71 72 module.exports = bisect;