-
-
Save jaysonmulwa/28bc8f78cab39aae26b045f99e51969d to your computer and use it in GitHub Desktop.
Calculating Shannon's entropy with JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Calculate Shannon's entropy for a string | |
*/ | |
module.exports = (str) => { | |
const set = {}; | |
str.split('').forEach( | |
c => (set[c] ? set[c]++ : (set[c] = 1)) | |
); | |
return Object.keys(set).reduce((acc, c) => { | |
const p = set[c] / str.length; | |
return acc - (p * (Math.log(p) / Math.log(2))); | |
}, 0); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment