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)issqrt(dot(v, v)). When you only compare distances, compare the squared values withdot(v, v)and skip thesqrt. - 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
sqrtwhen it is not needed. Comparinglength(p) < ris the same asdot(p, p) < r * r, which avoids the root entirely.
Related functions
pow()
Returns x raised to the power y. On values between 0.0 and 1.0 it bends a straight ramp into a curve.
inversesqrt()
Returns 1.0 / sqrt(x). Common in normalization and in light falloff that fades with distance.
length()
Returns the length of a vector, its distance from the origin. length(p) is the starting point for drawing circles.