Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is x != 0.0 a safe check against DivideByZeroException?

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.

like image 517
Kit Fisto Avatar asked Jan 17 '23 13:01

Kit Fisto


2 Answers

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).

like image 171
Jon Skeet Avatar answered Jan 28 '23 11:01

Jon Skeet


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.

like image 29
Stefan Paul Noack Avatar answered Jan 28 '23 10:01

Stefan Paul Noack