time-to-botec

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

entropy.js (2012B)


      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 digamma = require( '@stdlib/math/base/special/digamma' );
     24 var gammaln = require( '@stdlib/math/base/special/gammaln' );
     25 var isnan = require( '@stdlib/math/base/assert/is-nan' );
     26 var ln = require( '@stdlib/math/base/special/ln' );
     27 
     28 
     29 // MAIN //
     30 
     31 /**
     32 * Returns the differential entropy of an F distribution.
     33 *
     34 * @param {PositiveNumber} d1 - numerator degrees of freedom
     35 * @param {PositiveNumber} d2 - denominator degrees of freedom
     36 * @returns {number} entropy
     37 *
     38 * @example
     39 * var v = entropy( 3.0, 7.0 );
     40 * // returns ~1.298
     41 *
     42 * @example
     43 * var v = entropy( 4.0, 12.0 );
     44 * // returns ~1.12
     45 *
     46 * @example
     47 * var v = entropy( 8.0, 7.0 );
     48 * // returns ~1.193
     49 *
     50 * @example
     51 * var v = entropy( 1.0, -0.1 );
     52 * // returns NaN
     53 *
     54 * @example
     55 * var v = entropy( -0.1, 1.0 );
     56 * // returns NaN
     57 *
     58 * @example
     59 * var v = entropy( 2.0, NaN );
     60 * // returns NaN
     61 *
     62 * @example
     63 * var v = entropy( NaN, 2.0 );
     64 * // returns NaN
     65 */
     66 function entropy( d1, d2 ) {
     67 	var half;
     68 	var hd1;
     69 	var hd2;
     70 	var out;
     71 
     72 	if (
     73 		isnan( d1 ) ||
     74 		isnan( d2 ) ||
     75 		d1 <= 0.0 ||
     76 		d2 <= 0.0
     77 	) {
     78 		return NaN;
     79 	}
     80 	half = ( d1 + d2 ) / 2.0;
     81 	hd1 = d1 / 2.0;
     82 	hd2 = d2 / 2.0;
     83 	out = ln( d2 / d1 ) + gammaln( hd1 ) + gammaln( hd2 ) - gammaln( half );
     84 	out += ( 1.0-hd1 ) * digamma( hd1 );
     85 	out += ( -1.0-hd2 ) * digamma( hd2 );
     86 	out += half * digamma( half );
     87 	return out;
     88 }
     89 
     90 
     91 // EXPORTS //
     92 
     93 module.exports = entropy;