search.js (1799B)
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 cdf = require( './../../../../../base/dists/negative-binomial/cdf' ); 24 25 26 // VARIABLES // 27 28 var methods; 29 30 31 // FUNCTIONS // 32 33 /** 34 * Performs a search to the left. 35 * 36 * @param {NonNegativeInteger} x - starting guess 37 * @param {Probability} k - probability 38 * @param {PositiveNumber} r - number of failures until experiment is stopped 39 * @param {Probability} p - success probability 40 * @returns {NonNegativeInteger} `k` quantile of the specified distribution 41 */ 42 function searchLeft( x, k, r, p ) { 43 while ( true ) { 44 if ( x === 0 || cdf( x - 1.0, r, p ) < k ) { 45 return x; 46 } 47 x -= 1; 48 } 49 } 50 51 /** 52 * Performs a search to the right. 53 * 54 * @param {NonNegativeInteger} x - starting guess 55 * @param {Probability} k - probability 56 * @param {PositiveNumber} r - number of failures until experiment is stopped 57 * @param {Probability} p - success probability 58 * @returns {NonNegativeInteger} `k` quantile of the specified distribution 59 */ 60 function searchRight( x, k, r, p ) { 61 while ( true ) { 62 x += 1; 63 if ( cdf( x, r, p ) >= k ) { 64 return x; 65 } 66 } 67 } 68 69 70 // MAIN // 71 72 methods = { 73 'left': searchLeft, 74 'right': searchRight 75 }; 76 77 78 // EXPORTS // 79 80 module.exports = methods;