Intrinsics1 min read

exp2

Computes 2 raised to a power.

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

Test exp2 in a live shader

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

Open Playground

Live Demo

The exp2 function returns 2^x, the base-2 exponential function.

Signature

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

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

Parameters

ParameterTypeDescription
xTThe exponent

Return Value

Returns 2 raised to the power x.

Example

bwsl
pipeline MipmapBlending {
fragment {
// Calculate mipmap level based on screen coverage
float2 texSize = float2(1024.0, 1024.0);
float2 duvdx = ddx(input.uv * texSize);
float2 duvdy = ddy(input.uv * texSize);
float maxDeriv = max(dot(duvdx, duvdx), dot(duvdy, duvdy));
float mipLevel = 0.5 * log2(maxDeriv);
// Convert back to texture scale factor
float scale = exp2(-mipLevel);
output.color = float4(scale, mipLevel / 10.0, 0.0, 1.0);
}
}

Common Use Cases

Mipmap Calculations

bwsl
// Calculate texture size at mip level
float mipScale = exp2(-mipLevel);
float2 mipSize = baseSize * mipScale;

HDR Exposure

bwsl
// Apply exposure as power of 2
float exposureScale = exp2(exposure);
float3 exposedColor = hdrColor * exposureScale;

Audio/Signal Processing

bwsl
// Convert decibels to linear
float linear = exp2(decibels / 6.0); // Approximate dB to linear

Octave-based Noise

bwsl
// Noise frequency per octave
float frequency = baseFreq * exp2(float(octave));

Bit Operations

bwsl
// Power of 2 for bit shifting equivalent
float powerOf2 = exp2(float(bitPosition));

Performance

On most GPUs, exp2 is faster than exp because it maps directly to hardware. When possible, reformulate exponentials to use base 2.

Conversion

To convert between bases: exp(x) = exp2(x / log(2)) and exp2(x) = exp(x * log(2)).

Compiled Output

When compiled to GLSL:

glsl
exp2(x)

When compiled to HLSL:

hlsl
exp2(x)

When compiled to Metal:

metal
exp2(x)

See Also

  • exp - e^x
  • log2 - Base-2 logarithm
  • pow - General power function