It appears that your issue lies in the necessity to utilize the base 2 logarithm instead of the natural logarithm. Fortunately, JavaScript since ES2015 includes a built-in function, Math.log2()
, for this purpose:
const val =[0.5035203893575573, 0.4964796106424427]
const shannonEntropy = (val: number[]) =>
val.map(v => -v * Math.log2(v)).reduce((x, y) => x + y, 0);
console.log(shannonEntropy(val)); // 0.9999642406577658
If you prefer to maintain ES5 compatibility, you can still achieve the desired outcome by using the natural log and multiplying the result by Math.LOG2E
:
const val =[0.5035203893575573, 0.4964796106424427]
const shannonEntropy = (val: number[]) =>
val.map(v => -v * Math.log(v)).reduce((x, y) => x + y, 0)*Math.LOG2E;
console.log(shannonEntropy(val)); // 0.9999642406577659
As you can observe, both approaches yield similar results (with any discrepancies attributed to numerical precision issues).
Trust this clarifies the matter; best of luck with your task!