In order to prevent 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 imprecisions, I wonder whether it is guaranteed that this function never throws a DivideByZeroException.
It wouldn't throw a DivideByZeroException
anyway, as you're dealing with double
arithmetic - it would just return infinity. Other values may return infinity, e.g. f(double.Epsilon)
.
The documentation says:
Dividing a floating-point value by zero will result in either positive infinity, negative infinity, or Not-a-Number (NaN) according to the rules of IEEE 754 arithmetic. 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 checking, but it may return positive infinity, negative infinity, or Not-a-Number (NaN) even if you check for 0.0
, for example when you divide a rather large value by a really small value so that the result exceeds the range covered by double.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With