factory.js (2030B)
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 betainc = require( '@stdlib/math/base/special/betainc' ); 25 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 26 var pow = require( '@stdlib/math/base/special/pow' ); 27 28 29 // MAIN // 30 31 /** 32 * Returns a function for evaluating the cumulative distribution function (CDF) for a Student's t distribution with degrees of freedom `v`. 33 * 34 * @param {PositiveNumber} v - degrees of freedom 35 * @returns {Function} CDF 36 * 37 * @example 38 * var cdf = factory( 0.5 ); 39 * var y = cdf( 3.0 ); 40 * // returns ~0.816 41 * 42 * y = cdf( 1.0 ); 43 * // returns ~0.699 44 */ 45 function factory( v ) { 46 if ( isnan( v ) || v <= 0.0 ) { 47 return constantFunction( NaN ); 48 } 49 return cdf; 50 51 /** 52 * Evaluates the cumulative distribution function (CDF) for a Student's t distribution. 53 * 54 * @private 55 * @param {number} x - input value 56 * @returns {Probability} evaluated CDF 57 * 58 * @example 59 * var y = cdf( 2.0 ); 60 * // returns <number> 61 */ 62 function cdf( x ) { 63 var x2; 64 var p; 65 var z; 66 if ( isnan( x ) ) { 67 return NaN; 68 } 69 if ( x === 0.0 ) { 70 return 0.5; 71 } 72 x2 = pow( x, 2.0 ); 73 if ( v > 2.0*x2 ) { 74 z = x2 / ( v + x2 ); 75 p = betainc( z, 0.5, v/2.0, true, true ) / 2.0; 76 } else { 77 z = v / ( v + x2 ); 78 p = betainc( z, v/2.0, 0.5, true, false ) / 2.0; 79 } 80 return ( x > 0.0 ) ? 1.0 - p : p; 81 } 82 } 83 84 85 // EXPORTS // 86 87 module.exports = factory;