Intrinsics1 min read

sqrt

Computes the square root.

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

Test sqrt in a live shader

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

Open Playground

Live Demo

The sqrt function returns the square root of the input value.

Signature

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

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

Parameters

ParameterTypeDescription
xTThe input value (must be >= 0)

Return Value

Returns the square root of x.

Example

bwsl
pipeline DistanceField {
fragment {
// Calculate distance from center
float2 centered = input.uv - 0.5;
float distSquared = centered.x * centered.x + centered.y * centered.y;
float dist = sqrt(distSquared);
// Create circular gradient
float gradient = 1.0 - smoothstep(0.0, 0.4, dist);
output.color = float4(float3(gradient), 1.0);
}
}

Common Use Cases

Distance Calculation

bwsl
// Euclidean distance (prefer length() for vectors)
float dist = sqrt(dx * dx + dy * dy);

Normal Reconstruction

bwsl
// Reconstruct Z from XY normal map
float2 normalXY = texNormal.xy * 2.0 - 1.0;
float normalZ = sqrt(1.0 - saturate(dot(normalXY, normalXY)));
float3 normal = float3(normalXY, normalZ);

Quadratic Formula

bwsl
// Solve quadratic equation
float discriminant = b * b - 4.0 * a * c;
if (discriminant >= 0.0) {
float sqrtD = sqrt(discriminant);
float t1 = (-b - sqrtD) / (2.0 * a);
float t2 = (-b + sqrtD) / (2.0 * a);
}

Physical Simulations

bwsl
// Orbital velocity
float orbitalVelocity = sqrt(gravitationalConstant * mass / radius);

Spherical Mapping

bwsl
// Convert to spherical coordinates
float r = sqrt(pos.x * pos.x + pos.y * pos.y + pos.z * pos.z);

Negative Values

sqrt(x) is undefined for negative values and will produce NaN. Always ensure the input is non-negative, or use sqrt(max(x, 0.0)) for safety.

Optimization

When you only need the square root for comparison, compare squared values instead: dist < threshold becomes distSquared < threshold * threshold.

Compiled Output

When compiled to GLSL:

glsl
sqrt(x)

When compiled to HLSL:

hlsl
sqrt(x)

See Also

  • rsqrt - Inverse square root (1/√x)
  • length - Vector magnitude
  • pow - Power function