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