Is x! = 0.0 a safe check for DivideByZeroException?

To throw a DivideByZeroException in C #, people often write things like

double f(double x) { if (x != 0.0) return 1000.0/x; else return 0.0; } 

Given the fact that floating point arithmetic always has inaccuracies, I wonder if it is guaranteed that this function never throws a DivideByZeroException.

+4
source share
2 answers

The documentation says:

Dividing the floating point value by zero will result in either positive infinity, negative infinity, or non-number (NaN) according to IEEE 754 arithmetic rules. Floating point operations never throw an exception. For more information, see Single and Double.

So yes, "it is guaranteed that this function never throws a DivideByZeroException." - even without any check, but it can return positive infinity, negative infinity or Not-a-Number (NaN), even if you check 0.0 , for example, when you divide a fairly large value by a very small value, the result exceeds the range, covered by double.

+1
source

In any case, he would not throw a DivideByZeroException , since you are dealing with double arithmetic - it will simply return infinity. Other values ​​may return infinity, for example. f(double.Epsilon) .

+8
source

Source: https://habr.com/ru/post/1395212/


All Articles