log2()
log2(x) The log2() function computes the logarithm of a number in base 2. This is particularly useful in computer science and information theory.
Syntax
log2(x)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | numeric | , | A numeric vector or scalar |
The argument x is typically a numeric vector, though log2() will attempt to coerce other types. The function is vectorized, so log2(c(2, 4, 8, 16)) computes the result for each element and returns a numeric vector of the same length. Negative inputs produce NaN with a warning since the logarithm is undefined for non-positive arguments, while log2(0) returns -Inf.
Examples
Basic usage
# Log base 2 of 2 is 1
log2(2)
# [1] 1
# Log base 2 of 8 is 3
log2(8)
# [1] 3
# Log base 2 of 1024 is 10
log2(1024)
# [1] 10
# Working with vectors
log2(c(1, 2, 4, 8, 16))
# [1] 0 1 2 3 4
These outputs follow directly from the definition of log base 2: log2(2^n) = n for any integer n. The vectorized call log2(c(1, 2, 4, 8, 16)) returns the exponents 0 through 4 because each value is an exact power of two. For non-power-of-two inputs, log2() returns a floating-point approximation — for example, log2(6) is roughly 2.585, which you can verify by computing 2^2.585.
Common patterns
Information theory
# Bits needed to represent n values
n <- 100
ceiling(log2(n))
# [1] 7
# Information entropy
probs <- c(0.5, 0.25, 0.125, 0.125)
-sum(probs * log2(probs))
# [1] 1.75
Shannon entropy uses log2() because information content is measured in bits. Each term -p * log2(p) represents the information contributed by an outcome with probability p. The result of 1.75 bits means you need on average fewer than 2 bits to encode each symbol from this distribution — a result that underlies Huffman coding, arithmetic coding, and all modern data compression algorithms in practical use.
Binary representations
# Find the bit position
x <- 16
log2(x)
# [1] 4
# Check if number is power of 2
is_power_of_2 <- function(n) n > 0 && (n & (n - 1)) == 0
is_power_of_2(8)
# [1] TRUE
is_power_of_2(10)
# [1] FALSE
The bitwise power-of-two test n & (n - 1) == 0 is exact for integer inputs and avoids floating-point rounding issues that would plague log2(n) == round(log2(n)). For large integers above 2^53, log2() loses precision because double-precision floats cannot represent every integer, making the bitwise approach the only reliable test for powers of two in that range.
Algorithm complexity
# Binary search complexity: O(log2(n))
n <- 1000
log2(n)
# [1] 9.965784
For a dataset of 1000 elements, binary search needs at most 10 comparisons to find any item, because ceiling(log2(1000)) is 10. This logarithmic scaling is why binary search outperforms linear search for large datasets: searching a million elements takes only about 20 comparisons instead of up to a million. Any algorithm that halves the search space each iteration inherits this O(log n) behavior.
When to use log2()
log2() is the natural choice in computer science and information theory contexts. Shannon entropy, information content, and binary search depth all use base-2 logarithms: log2(n) gives the number of bits needed to represent n values. The number of comparisons in a binary search of n items is ceiling(log2(n)).
For genomics and expression analysis, fold changes are conventionally expressed in log2, a log2 fold change of 1 means the expression doubled, -1 means it halved. This is why volcano plots in differential expression analysis use log2(fold_change) on the x-axis.
log2() is equivalent to log(x, base = 2) but implemented as a C primitive, making it faster for large vectors. For values close to 1, where numerical precision matters, log2(1 + x) can lose precision, consider log1p(x) / log(2) for better accuracy near zero.
log2() is a C primitive that is faster than log(x, base = 2) for the same computation. It returns NaN for negative inputs with a warning, -Inf for zero, and Inf for Inf. The function is vectorized and propagates NA values. When all values in a vector are powers of 2, the output is a clean integer-valued double, a useful property for verifying dimension relationships in image processing or buffer sizing.
In machine learning, log2 is used to measure information gain in decision tree algorithms and to express model complexity. When evaluating binary classifiers, log2 entropy H = -sum(p * log2(p)) measures the purity of a split. Many implementations use log() (natural log) internally for speed, then divide by log(2) to convert, but for human-readable entropy in bits, calling log2() directly gives the canonical unit with less code.
In practical usage, log2() returns exact integer results only for exact powers of 2. For values like log2(6), the result is irrational and stored as a floating-point approximation. When testing whether a number is a power of two, avoid comparing log2(n) == round(log2(n)) due to floating-point precision — use the bitwise test n > 0 && bitwAnd(n, n - 1L) == 0L for integer inputs, which gives exact results.
Computing fold changes in bioinformatics
# RNA-seq expression values (counts per gene)
control <- c(120, 45, 890, 2300, 15)
treated <- c(180, 90, 1780, 6900, 10)
# Compute log2 fold change for each gene
log2_fc <- log2(treated / control)
log2_fc
# [1] 0.585 1.000 1.000 1.585 -0.585
# Genes with at least 2-fold upregulation (log2FC >= 1)
upregulated <- which(log2_fc >= 1)
upregulated
# [1] 2 3 4
Fold changes are the standard unit in differential expression analysis because log2 transforms make the scale symmetric: a doubling is +1 and a halving is −1. Genes 2, 3, and 4 are upregulated at least twofold since their log2 fold changes meet or exceed 1. For the fifth gene, the negative value means expression dropped — log2(10/15) ≈ -0.585 — corresponding to roughly a 33% decrease. Volcano plots use log2 fold change on the x-axis and −log10(p-value) on the y-axis, combining these two transformations to highlight both large effects and high statistical confidence.