Intrinsics1 min read

log2

Computes the base-2 logarithm.

Reading Time
1 min
Word Count
140
Sections
12
Try It Live

Test log2 in a live shader

Open the playground, start from a visual preset, and wire log2 into the fragment stage to see how it behaves with real values.

Open Playground

Live Demo

The log2 function returns the base-2 logarithm of the input value.

Signature

bwsl
log2 :: (T x) -> T {...}

Where T can be float, float2, float3, or float4.

Parameters

ParameterTypeDescription
xTThe input value (must be > 0)

Return Value

Returns the base-2 logarithm of x.

Example

bwsl
pipeline MipmapLevel {
fragment {
// Calculate appropriate mipmap level
float2 texSize = float2(textureWidth, textureHeight);
float2 duvdx = ddx(input.uv) * texSize;
float2 duvdy = ddy(input.uv) * texSize;
float maxDelta = max(dot(duvdx, duvdx), dot(duvdy, duvdy));
float mipLevel = 0.5 * log2(maxDelta);
// Sample with calculated LOD
float4 color = sample_lod(albedoTex, input.uv, mipLevel);
output.color = color;
}
}

Common Use Cases

Mipmap Level Calculation

bwsl
// Determine which mip level to sample
float coverage = max(ddx(uv).x, ddy(uv).y) * textureSize;
float mip = log2(coverage);

Power-of-Two Detection

bwsl
// Check if value is power of 2
float logVal = log2(float(value));
bool isPowerOf2 = fract(logVal) < 0.001;

Bit Position

bwsl
// Find highest set bit position (approximate)
int bitPos = int(floor(log2(float(value))));

LOD Bias

bwsl
// Calculate LOD with sharpening bias
float baseLOD = log2(screenSpaceDerivative);
float sharpLOD = baseLOD - sharpnessBias;

Octave Calculation

bwsl
// Determine octave from frequency
float octave = log2(frequency / baseFrequency);

Performance

log2 is typically faster than log on GPU hardware since it maps directly to the native instruction. Prefer log2 when the base doesn't matter or can be adjusted.

Domain

log2(x) is undefined for x <= 0. Returns negative infinity for x = 0.

Compiled Output

When compiled to GLSL:

glsl
log2(x)

When compiled to HLSL:

hlsl
log2(x)

When compiled to Metal:

metal
log2(x)

See Also

  • log - Natural logarithm
  • exp2 - Base-2 exponential
  • pow - Power function