time-to-botec

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

logpdf.js (2105B)


      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 isnan = require( '@stdlib/math/base/assert/is-nan' );
     24 var gammaln = require( '@stdlib/math/base/special/gammaln' );
     25 var ln = require( '@stdlib/math/base/special/ln' );
     26 var NINF = require( '@stdlib/constants/float64/ninf' );
     27 var PINF = require( '@stdlib/constants/float64/pinf' );
     28 var LN2 = require( '@stdlib/constants/float64/ln-two' );
     29 
     30 
     31 // MAIN //
     32 
     33 /**
     34 * Evaluates the natural logarithm of the probability density function (PDF) for a chi distribution with degrees of freedom `k` at a value `x`.
     35 *
     36 * @param {number} x - input value
     37 * @param {NonNegativeNumber} k - degrees of freedom
     38 * @returns {number} evaluated logPDF
     39 *
     40 * @example
     41 * var y = logpdf( 0.3, 4.0 );
     42 * // returns ~-4.35
     43 *
     44 * @example
     45 * var y = logpdf( 0.7, 0.7 );
     46 * // returns ~-0.622
     47 *
     48 * @example
     49 * var y = logpdf( -1.0, 0.5 );
     50 * // returns -Infinity
     51 *
     52 * @example
     53 * var y = logpdf( 0.0, NaN );
     54 * // returns NaN
     55 *
     56 * @example
     57 * var y = logpdf( NaN, 2.0 );
     58 * // returns NaN
     59 *
     60 * @example
     61 * // Negative degrees of freedom:
     62 * var y = logpdf( 2.0, -1.0 );
     63 * // returns NaN
     64 */
     65 function logpdf( x, k ) {
     66 	var out;
     67 	var kh;
     68 	if (
     69 		isnan( x ) ||
     70 		isnan( k ) ||
     71 		k < 0.0
     72 	) {
     73 		return NaN;
     74 	}
     75 	if ( k === 0.0 ) {
     76 		// Point mass at 0...
     77 		return ( x === 0.0 ) ? PINF : NINF;
     78 	}
     79 	if ( x < 0.0 || x === PINF ) {
     80 		return NINF;
     81 	}
     82 	kh = k / 2.0;
     83 	out = ( ( 1.0-kh ) * LN2 ) + ( ( k-1.0 ) * ln( x ) ) - ( (x*x) / 2.0 );
     84 	out -= gammaln( kh );
     85 	return out;
     86 }
     87 
     88 
     89 // EXPORTS //
     90 
     91 module.exports = logpdf;