Remix.run Logo
exDM69 2 days ago

It's not always necessary to check for inf/NaN explicitly using isinf/isnan. Both inf and NaN are floating point values with well defined semantics.

I'll give two examples from a recent project where I very intentionally divided by zero. First one was about solving a zero in a derivative and check if it falls on 0..1 range. This exploits the fact that (x < NaN) is always false and comparisons with +/- inf behave as expected.

    float t = a / b; // might divide by zero. NaN if a and b == 0.0, +/- inf if b == 0.0
    if (t > 0.0 && t < 1.0) {
        // we don't get here if t is +/- inf or nan
        split_at(t); // do the thing
    }
The second one was similar, but clamping to 0..1 range using branchless simd min/max.

    f32x8 x = a / b; // might divide by zero
    return simd_min(simd_max(0.0, x), 1.0); // returns 0 for -inf or nan, 1 for +inf
In both of these cases, explicitly checking for division by zero or isinf/isnan would've been (worse than) useless because just using the inf/NaN values gave the correct answer for what comes next.