time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

factory.js (2080B)


      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 constantFunction = require( '@stdlib/utils/constant-function' );
     24 var isnan = require( '@stdlib/math/base/assert/is-nan' );
     25 var log1p = require( '@stdlib/math/base/special/log1p' );
     26 var ceil = require( '@stdlib/math/base/special/ceil' );
     27 var max = require( '@stdlib/math/base/special/max' );
     28 var ln = require( '@stdlib/math/base/special/ln' );
     29 var PINF = require( '@stdlib/constants/float64/pinf' );
     30 
     31 
     32 // MAIN //
     33 
     34 /**
     35 * Returns a function for evaluating the quantile function for a geometric distribution with success probability `p`.
     36 *
     37 * @param {Probability} p - success probability
     38 * @returns {Function} quantile function
     39 *
     40 * @example
     41 * var quantile = factory( 0.4 );
     42 * var y = quantile( 0.4 );
     43 * // returns 0
     44 *
     45 * y = quantile( 0.8 );
     46 * // returns 3
     47 *
     48 * y = quantile( 1.0 );
     49 * // returns Infinity
     50 */
     51 function factory( p ) {
     52 	if ( isnan( p ) || p < 0.0 || p > 1.0 ) {
     53 		return constantFunction( NaN );
     54 	}
     55 	return quantile;
     56 
     57 	/**
     58 	* Evaluates the quantile function for a geometric distribution.
     59 	*
     60 	* @private
     61 	* @param {Probability} r - input value
     62 	* @returns {NonNegativeInteger} evaluated quantile function
     63 	*
     64 	* @example
     65 	* var y = quantile( 0.3 );
     66 	* // returns <number>
     67 	*/
     68 	function quantile( r ) {
     69 		if ( isnan( r ) || r < 0.0 || r > 1.0 ) {
     70 			return NaN;
     71 		}
     72 		if ( r === 1.0 ) {
     73 			return PINF;
     74 		}
     75 		return max( 0.0, ceil( (ln(1.0-r) / log1p(-p)) - (1.0 + 1e-12) ) );
     76 	}
     77 }
     78 
     79 
     80 // EXPORTS //
     81 
     82 module.exports = factory;