Math.LOG2E
Math.LOG2E is a static property of the Math object that represents the base-2 logarithm of E (Euler’s number), approximately 1.4426950408889634. It is a read-only constant; you cannot change its value.
This constant equals log2(e) and is useful when working with logarithmic calculations in base 2, computer science algorithms, and information theory.
Syntax
Math.LOG2E
Value
Math.LOG2E; // 1.4426950408889634
Examples
Basic Usage
console.log(Math.LOG2E);
// 1.4426950408889634
Relationship with Natural Logarithm
Math.LOG2E is the reciprocal of Math.LN2:
console.log(Math.LOG2E === 1 / Math.LN2);
// true
console.log(Math.LOG2E * Math.LN2);
// 1
Calculating Base-2 Logarithms
You can use this constant to convert natural logarithms to base-2:
function log2(x) {
return Math.log(x) * Math.LOG2E;
}
console.log(log2(2));
// 1
console.log(log2(4));
// 2
console.log(log2(8));
// 3
console.log(log2(1024));
// 10
Information Theory Applications
In information theory, Math.LOG2E helps convert between natural entropy and bits:
// Convert natural logarithm entropy to bits
function entropyToBits(natEntropy) {
return natEntropy * Math.LOG2E;
}
console.log(entropyToBits(0.6931471805599453));
// 1 (approximately 1 bit)
Algorithm Analysir
When analyzing algorithms with logarithmic complexity:
// Calculate number of comparisons in binary search
function binarySearchComparisons(n) {
return Math.ceil(Math.log2(n));
}
console.log(binarySearchComparisons(100));
// 7
console.log(binarySearchComparisons(1000));
// 10
console.log(binarySearchComparisons(1048576));
// 20
Bit Length Calculations
Math.LOG2E is useful for determining how many bits are needed to represent a number:
function bitLength(n) {
return Math.floor(Math.log2(n)) + 1;
}
console.log(bitLength(1));
// 1
console.log(bitLength(7));
// 3
console.log(bitLength(255));
// 8
console.log(bitLength(1024));
// 11
Common Patterns
Quick Base-2 Logarithm
// Instead of Math.log(x) / Math.LN2
const quickLog2 = x => Math.log(x) * Math.LOG2E;
console.log(quickLog2(16));
// 4
Comparing Log Bases
// Relationship between different logarithm bases
const log10 = x => Math.log(x) / Math.LN10;
const log2 = x => Math.log(x) * Math.LOG2E;
console.log(log2(100));
// 6.643856189774724
console.log(log10(100));
// 2
Why Use Math.LOG2E?
Using Math.LOG2E instead of hardcoding 1.4426950408889634 provides several advantages:
- Precision — The constant is defined to full floating-point precision by the JavaScript engine
- Readability — Code clearly expresses the mathematical concept log2(e)
- Standardization — Matches mathematical notation in formulas and algorithms
- Efficiency — The value is computed once by the JavaScript engine, not on every calculation
See Also
- Math.LN2 — the natural logarithm of 2
- Math.LN10 — the natural logarithm of 10
- Math.log2() — returns the base-2 logarithm of a number
- Math.log() — returns the natural logarithm of a number