View Full Version : Divide by zero

12-30-2010, 10:46 AM
What happens if you divide by zero in a fragment shader? Will this result in a cataclysm. I am just trying to limit values that can be passed to my shaders, and am wondering do I need to check for this, or will the hardware just return say 0 for a divide by zero.

Dark Photon
12-30-2010, 10:59 AM
From the GLSL 4.0 spec:

Similarly, treatment of conditions such as divide by 0 may lead to an unspecified result, but in no case
should such a condition lead to the interruption or termination of processing. Generally, there are no
signaling NaNs, and operating on NaNs (Not a Number) or infs (positive or negative infinities) gives
undefined results.
From the GLSL 4.1 spec:

The precision of stored single- and double-precision floating-point variables is defined by the IEEE 754
standard for 32-bit and 64-bit floating-point numbers. This includes support for NaNs (Not a Number) and Infs (positive or negative infinities). The following rules apply to both single and double-precision operations: Dividing by 0 results in the appropriately signed IEEE Inf. Any denormalized value input into a shader or potentially generated by an operation in a shader can be flushed to 0. In general, correct signedness of 0 is not required. The rounding mode cannot be set and is undefined. Support for signaling NaNs is not required and exceptions are never raised. Operations and built-in functions that operate on a NaN are not required to return a NaN as the result.

genBType isnan (genType x)
genBType isnan (genDType x)
- Returns true if x holds a NaN. Returns false otherwise.
genBType isinf (genType x)
genBType isinf (genDType x)
- Returns true if x holds a positive infinity or negative infinity. Returns false otherwise.

So sounds like if you're using GLSL pre-4.1, then the results are undefined but it won't crash the GPU (so you should avoid these cases, by clamping denominators that might be 0 and such).

With GLSL 4.1 (last-gen GPUs only) you can sense these conditions after-the-fact. But not too far after-the-fact (for NaNs) since there's no requirement that the GPU propagate them.

12-30-2010, 11:09 AM
thanks, I think i'll just stick to checking for zero being passed to my shader and clamp it to slightly above zero :)