entropy.js (2299B)
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 sumSeries = require( '@stdlib/math/base/tools/sum-series' ); 24 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 25 var factorialln = require( '@stdlib/math/base/special/factorialln' ); 26 var factorial = require( '@stdlib/math/base/special/factorial' ); 27 var exp = require( '@stdlib/math/base/special/exp' ); 28 var ln = require( '@stdlib/math/base/special/ln' ); 29 30 31 // FUNCTIONS // 32 33 /** 34 * Returns a function to retrieve elements of the series \\( \sum_{k=0}^{\infty} \frac{ \lambda^k \log(k!) }{ k! } \\). 35 * 36 * @private 37 * @param {NonNegativeNumber} lambda - mean parameter 38 * @returns {Function} function to retrieve series elements 39 */ 40 function seriesClosure( lambda ) { 41 var lk; 42 var k; 43 k = 1; 44 lk = lambda; 45 return seriesElement; 46 47 /** 48 * Returns the current series element. 49 * 50 * @private 51 * @returns {number} series element 52 */ 53 function seriesElement() { 54 k += 1; 55 lk *= lambda; 56 return lk * factorialln( k ) / factorial( k ); 57 } 58 } 59 60 61 // MAIN // 62 63 /** 64 * Returns the entropy of a Poisson distribution. 65 * 66 * @param {NonNegativeNumber} lambda - mean parameter 67 * @returns {PositiveNumber} entropy 68 * 69 * @example 70 * var v = entropy( 9.0 ); 71 * // returns ~2.508 72 * 73 * @example 74 * var v = entropy( 1.0 ); 75 * // returns ~1.305 76 * 77 * @example 78 * var v = entropy( -0.2 ); 79 * // returns NaN 80 * 81 * @example 82 * var v = entropy( NaN ); 83 * // returns NaN 84 */ 85 function entropy( lambda ) { 86 var gen; 87 var out; 88 if ( isnan( lambda ) || lambda < 0.0 ) { 89 return NaN; 90 } 91 if ( lambda === 0.0 ) { 92 return 0.0; 93 } 94 gen = seriesClosure( lambda ); 95 out = lambda * ( 1.0-ln(lambda) ); 96 out += exp( -lambda ) * sumSeries( gen ); 97 return out; 98 } 99 100 101 // EXPORTS // 102 103 module.exports = entropy;