Intrinsics1 min read

rsqrt

Computes the inverse square root.

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

Test rsqrt in a live shader

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

Open Playground

Live Demo

The rsqrt function returns the reciprocal of the square root, computed as 1.0 / sqrt(x). This is often faster than computing the division separately.

Signature

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

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

Parameters

ParameterTypeDescription
xTThe input value (must be > 0)

Return Value

Returns 1.0 / sqrt(x).

Example

bwsl
pipeline FastNormalize {
fragment {
// Manual vector normalization using rsqrt
float3 vec = input.worldPos - cameraPos;
float lenSquared = dot(vec, vec);
float invLen = rsqrt(lenSquared);
float3 normalized = vec * invLen;
output.color = float4(normalized * 0.5 + 0.5, 1.0);
}
}

Common Use Cases

Manual Normalization

bwsl
// Normalize a vector manually
float invLength = rsqrt(dot(v, v));
float3 normalized = v * invLength;

Physics Calculations

bwsl
// Inverse distance for gravity falloff
float distSquared = dot(delta, delta);
float invDist = rsqrt(distSquared);
float3 force = delta * invDist * invDist * invDist * gravityStrength;

Lighting Attenuation

bwsl
// Fast inverse distance
float invDist = rsqrt(dot(lightVec, lightVec));
float attenuation = invDist * invDist;

Quaternion Normalization

bwsl
// Normalize quaternion
float invMag = rsqrt(dot(q, q));
float4 normalizedQ = q * invMag;

Distance-Based Scaling

bwsl
// Scale inversely with distance
float distSq = dot(offset, offset);
float scale = rsqrt(distSq) * baseScale;

Performance

On many GPUs, rsqrt is a single hardware instruction and faster than 1.0 / sqrt(x). The compiler will typically optimize division by sqrt, but using rsqrt directly makes the intent clear.

Zero Values

rsqrt(0) is undefined and will produce infinity or NaN. Always ensure the input is positive, or add a small epsilon: rsqrt(x + 0.0001).

Compiled Output

When compiled to GLSL:

Uses the target backend's native reciprocal-square-root operation.

When compiled to HLSL:

hlsl
rsqrt(x)

When compiled to Metal:

metal
rsqrt(x)

See Also