GLSL Learning

GLSL built-in function

log2()

Returns the base-2 logarithm of x: how many times you double 1.0 to reach x. The inverse of exp2.

Syntax

float log2(float x)
vec2 log2(vec2 x)
vec3 log2(vec3 x)

Parameters

x
A value greater than 0.

Return value

The base-2 logarithm of x.

Live example

Edit the code and the preview updates as you type.

How it works

log2(x) counts doublings: log2(1.0) is 0, log2(2.0) is 1, log2(8.0) is 3, and log2(0.5) is -1.

In the example every ring covers one doubling of distance from the center: 0.125 to 0.25, 0.25 to 0.5, 0.5 to 1.0. The rings therefore get wider as they go out, but each one looks like a scaled copy of the next, which creates a seamless, endless zoom.

Typical uses

  • Levels of detail: log2(size) picks which mip level or octave to use.
  • Fractal zooms: rings or tiles that repeat at every doubling.
  • Counting octaves: log2(maxFrequency / baseFrequency).

Common mistakes

  • Zero or negative input, which is undefined. Add a tiny offset.
  • Expecting an integer. log2(3.0) is about 1.585; wrap in floor if you need the level number.

Related functions