time-to-botec

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

quantile.js (2088B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2020 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 isPositiveInteger = require( '@stdlib/math/base/assert/is-positive-integer' );
     24 var isfinite = require( '@stdlib/math/base/assert/is-finite' );
     25 var isnan = require( '@stdlib/math/base/assert/is-nan' );
     26 var exp = require( '@stdlib/math/base/special/exp' );
     27 var LN2 = require( '@stdlib/constants/float64/ln-two' );
     28 var weights = require( './weights.js' );
     29 
     30 
     31 // MAIN //
     32 
     33 /**
     34 * Evaluates the quantile function of the Wilcoxon signed rank test statistic with `n` observations.
     35 *
     36 * @param {Probability} p - input value
     37 * @param {PositiveInteger} n - number of observations
     38 * @returns {NonNegativeInteger} evaluated quantile function
     39 *
     40 * @example
     41 * var y = quantile( 0.8, 5 );
     42 * // returns 11
     43 *
     44 * @example
     45 * var y = quantile( 0.5, 4 );
     46 * // returns 5
     47 *
     48 * @example
     49 * var y = quantile( 1.1, 5 );
     50 * // returns NaN
     51 *
     52 * @example
     53 * var y = quantile( -0.2, 5 );
     54 * // returns NaN
     55 *
     56 * @example
     57 * var y = quantile( NaN, 5 );
     58 * // returns NaN
     59 *
     60 * @example
     61 * var y = quantile( 0.0, NaN );
     62 * // returns NaN
     63 */
     64 function quantile( p, n ) {
     65 	var pui;
     66 	var q;
     67 	var r;
     68 	if ( isnan( n ) || !isPositiveInteger( n ) || !isfinite( n ) ) {
     69 		return NaN;
     70 	}
     71 	if ( isnan( p ) || p < 0.0 || p > 1.0 ) {
     72 		return NaN;
     73 	}
     74 	if ( p === 0.0 ) {
     75 		return 0;
     76 	}
     77 	if ( p === 1.0 ) {
     78 		return ( n * ( n + 1 ) ) / 2;
     79 	}
     80 	pui = exp( -n * LN2 );
     81 	r = 0;
     82 	q = -1;
     83 	while ( r < p ) {
     84 		q += 1;
     85 		r += pui * weights( q, n );
     86 	}
     87 	return q;
     88 }
     89 
     90 
     91 // EXPORTS //
     92 
     93 module.exports = quantile;