time-to-botec

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

factory.js (2066B)


      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 isnan = require( '@stdlib/math/base/assert/is-nan' );
     25 var betaln = require( '@stdlib/math/base/special/betaln' );
     26 var sqrt = require( '@stdlib/math/base/special/sqrt' );
     27 var pow = require( '@stdlib/math/base/special/pow' );
     28 var ln = require( '@stdlib/math/base/special/ln' );
     29 
     30 
     31 // MAIN //
     32 
     33 /**
     34 * Returns a function for evaluating the natural logarithm of the probability density function (PDF) for a Student's t distribution with `v` degrees of freedom.
     35 *
     36 * @param {PositiveNumber} v - degrees of freedom
     37 * @returns {Function} logPDF
     38 *
     39 * @example
     40 * var logpdf = factory( 1.0 );
     41 * var y = logpdf( 3.0 );
     42 * // returns ~-3.447
     43 *
     44 * y = logpdf( 1.0 );
     45 * // returns ~-1.838
     46 */
     47 function factory( v ) {
     48 	var exponent;
     49 	var betaTerm;
     50 
     51 	if ( isnan( v ) || v <= 0 ) {
     52 		return constantFunction( NaN );
     53 	}
     54 	betaTerm = ln( sqrt( v ) ) + betaln( v/2.0, 0.5 );
     55 	exponent = ( 1.0 + v ) / 2.0;
     56 	return logpdf;
     57 
     58 	/**
     59 	* Evaluates the natural logarithm of the probability density function (PDF) for a Student's t distribution.
     60 	*
     61 	* @private
     62 	* @param {number} x - input value
     63 	* @returns {number} evaluated logPDF
     64 	*
     65 	* @example
     66 	* var y = logpdf( 2.3 );
     67 	* // returns <number>
     68 	*/
     69 	function logpdf( x ) {
     70 		if ( isnan( x ) ) {
     71 			return NaN;
     72 		}
     73 		return ( exponent * ln( v / ( v + pow( x, 2.0 ) ) ) ) - betaTerm;
     74 	}
     75 }
     76 
     77 
     78 // EXPORTS //
     79 
     80 module.exports = factory;