time-to-botec

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

logcdf.js (2119B)


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