cdf.js (2146B)
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 round = require( '@stdlib/math/base/special/round' ); 27 var exp = require( '@stdlib/math/base/special/exp' ); 28 var LN2 = require( '@stdlib/constants/float64/ln-two' ); 29 var weights = require( './weights.js' ); 30 31 32 // MAIN // 33 34 /** 35 * Evaluates the cumulative distribution function (CDF) of the Wilcoxon signed rank test statistic with `n` observations. 36 * 37 * @param {number} x - input value 38 * @param {PositiveInteger} n - number of observations 39 * @returns {Probability} evaluated CDF 40 * 41 * @example 42 * var y = cdf( 7.0, 9 ); 43 * // returns ~0.037 44 * 45 * @example 46 * var y = cdf( 7.0, 6 ); 47 * // returns ~0.281 48 * 49 * @example 50 * var y = cdf( -1.0, 40 ); 51 * // returns 0.0 52 * 53 * @example 54 * var y = cdf( NaN, 10 ); 55 * // returns NaN 56 * 57 * @example 58 * var y = cdf( 0.0, NaN ); 59 * // returns NaN 60 * 61 * @example 62 * var y = cdf( 2.0, -1 ); 63 * // returns NaN 64 * 65 * @example 66 * var y = cdf( 2.0, 1.8 ); 67 * // returns NaN 68 */ 69 function cdf( x, n ) { 70 var mlim; 71 var pui; 72 var i; 73 var p; 74 if ( 75 isnan( x ) || 76 !isPositiveInteger( n ) || 77 !isfinite( n ) 78 ) { 79 return NaN; 80 } 81 if ( x < 0.0 ) { 82 return 0.0; 83 } 84 x = round( x ); 85 mlim = n * ( n + 1 ) / 2; 86 if ( x >= mlim ) { 87 return 1.0; 88 } 89 pui = exp( -n * LN2 ); 90 p = 0; 91 for ( i = 0; i <= x; i++ ) { 92 p += weights( i, n ) * pui; 93 } 94 return p; 95 } 96 97 98 // EXPORTS // 99 100 module.exports = cdf;