GLSL Learning

GLSL built-in function

sqrt()

Returns the square root of x. For values between 0.0 and 1.0 it lifts the low end, rising fast and then flattening.

Syntax

float sqrt(float x)
vec2 sqrt(vec2 x)
vec3 sqrt(vec3 x)
vec4 sqrt(vec4 x)

Parameters

x
The value to take the square root of. Must be greater than or equal to 0.

Return value

The square root of x, with the same type as x.

Live example

Edit the code and the preview updates as you type.

How it works

sqrt(x) is the number that, multiplied by itself, gives x: sqrt(0.25) is 0.5.

In shaders it often appears in geometry. A unit sphere satisfies x*x + y*y + z*z = 1, so the height of the sphere above a pixel is z = sqrt(1.0 - x*x - y*y). The example uses that height to build a surface normal and light a sphere without any 3D geometry.

On the 0..1 range sqrt(x) is the same as pow(x, 0.5): it lifts small values a lot and large values only a little.

Typical uses

  • Fake spheres: the height formula above.
  • Distances: length(v) is sqrt(dot(v, v)). When you only compare distances, compare the squared values with dot(v, v) and skip the sqrt.
  • Brightening dark gradients: sqrt(t) makes a ramp brighter in its dark part.

Common mistakes

  • Taking the root of a negative number. sqrt(-0.01) is undefined and usually NaN, which shows up as black pixels at shape edges. Guard it: sqrt(max(x, 0.0)).
  • Calling sqrt when it is not needed. Comparing length(p) < r is the same as dot(p, p) < r * r, which avoids the root entirely.

Related functions

Tutorials that use sqrt()