Hacker News new | ask | show | jobs
by blahblahblah 5487 days ago
Regarding #3: Division by zero should be a recoverable error in many programming situations. That's part of the beauty of NaN as defined by the IEEE standard for floating point numbers. It's quite a handy thing to be able to just do the operation and sort out the NaNs afterward. Suppose, for example, that you want to calculate the pixel-wise percent change in intensity between two grayscale images A and B. In a language with good built-in support for matrix datatypes, such as MATLAB, the ability to handle division by zero gracefully can quite often simplify the code.

result = (A-B)./A*100;

Now I can just use the isfinite function to produce a matrix of logical values that tells me which pixel locations have valid values (simultaneously handling the case of numerical overflow). Granted, this doesn't do much to simplify the code above. We could have just checked beforehand to find the pixels of A that had zero values. However, if you have a complicated expression involving multiple divisions, logarithms, or other functions that are undefined for some portion of the real numbers, treating these situations as "recoverable" in some sense allows you to write cleaner, more readable code if your implementation language permits you to just do the operation and check for NaN values (+Inf and -Inf too) afterward.