rsqrt
Computes the inverse square root.
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 PlaygroundLive 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
rsqrt :: (T x) -> T {...}
Where T can be float, float2, float3, or float4.
Parameters
| Parameter | Type | Description |
|---|---|---|
x | T | The input value (must be > 0) |
Return Value
Returns 1.0 / sqrt(x).
Example
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
// Normalize a vector manually
float invLength = rsqrt(dot(v, v));
float3 normalized = v * invLength;Physics Calculations
// Inverse distance for gravity falloff
float distSquared = dot(delta, delta);
float invDist = rsqrt(distSquared);
float3 force = delta * invDist * invDist * invDist * gravityStrength;Lighting Attenuation
// Fast inverse distance
float invDist = rsqrt(dot(lightVec, lightVec));
float attenuation = invDist * invDist;Quaternion Normalization
// Normalize quaternion
float invMag = rsqrt(dot(q, q));
float4 normalizedQ = q * invMag;Distance-Based Scaling
// 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:
rsqrt(x)
When compiled to Metal:
rsqrt(x)