Intrinsics2 min read

isnan

Componentwise test for IEEE-754 NaN values.

Reading Time
2 min
Word Count
216
Sections
10
Try It Live

Test isnan in a live shader

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

Open Playground

Live Demo Pending

This intrinsic does not yet have a self-contained interactive preview. Compute-only and external-resource intrinsics need a different demo path than the current fragment and 3D showcases.

The isnan function returns true for each component that is a NaN (not-a-number). Scalar input produces a bool; vector input produces a bvecN of the same width.

Signature

bwsl
isnan :: (float x) -> bool
isnan :: (float2 x) -> bool2
isnan :: (float3 x) -> bool3
isnan :: (float4 x) -> bool4

Parameters

ParameterTypeDescription
xfloat, float2, float3, float4Value(s) to classify

Return Value

Returns a bool (or bvecN) where each component is true iff the corresponding input component is NaN. No other operation produces true+0.0, -0.0, ±inf, and normal / denormal finite values all return false.

Example

bwsl
pipeline SafeDivide {
fragment {
float3 n = input.normal;
float denom = dot(n, n);
float result = 1.0 / denom; // may produce NaN if denom == 0
if (isnan(result)) {
result = 0.0; // scrub out bad pixels
}
output.color = float4(result.xxx, 1.0);
}
}

Common Use Cases

Scrubbing Intermediate NaNs

bwsl
// Replace NaN components with a sentinel value before further math.
float3 safe = float3(
isnan(value.x) ? 0.0 : value.x,
isnan(value.y) ? 0.0 : value.y,
isnan(value.z) ? 0.0 : value.z
);

Componentwise Plus any

bwsl
// Flag a pixel if any channel is NaN.
bool3 bad = isnan(color.rgb);
if (any(bad)) {
output.color = float4(1.0, 0.0, 1.0, 1.0);
return;
}

Guarding Against Bad User Input

bwsl
// Compute shader reading from an untrusted buffer.
float v = resources.input[idx];
resources.output[idx] = isnan(v) ? 0.0 : v;

Fast-Math May Elide

Aggressive fast-math compilation (outside of BWSL's default SPIR-V path) can legally assume values are never NaN and fold isnan(x) to false. BWSL's backends emit the IEEE-correct operation (OpIsNan / isnan), but be aware when hand-editing the generated HLSL / GLSL.

Remember NaN != NaN

Without isnan, the idiomatic portable detection is x != x — only NaN fails that self-comparison. isnan(x) is clearer and hits the hardware-level opcode directly.

Compiled Output

When compiled to GLSL:

glsl
isnan(x)

When compiled to HLSL:

hlsl
isnan(x)

When compiled to Metal:

msl
isnan(x)

When compiled to SPIR-V:

Uses the OpIsNan instruction directly. The result type's component count matches the input.

See Also

  • isinf - Componentwise test for +/-infinity
  • any - Reduce a bvecN to a scalar bool
  • select - Branchless replacement of bad values