Is it a good practice to add a very small number to the divisor not to deal with division by zero exception?

1.9k views Asked by At

I want to keep my code clean and avoid unnecessary IF branches.
Is it a good practice to add a very small number to the divisor not to deal with division by zero exception? Is the below code considered a good practise?
I know that such comparison not purely 100% accurate in this case but let's it does not matter.

double safeDivision(double dividend, double divisor)
{
    return (dividend + Double.MIN_VALUE)/(divisor + Double.MIN_VALUE);
}
2

There are 2 answers

2
Igino Boffa On BEST ANSWER

No, it can give unwanted results. How do you deal with numbers coming off an "adjusted" division by 0?

A working code is always better then a clean but potentially bugged code

5
Lukas Eder On

Why worry about this in the context of double?

System.out.println( 1.0 / 0.0);
System.out.println( 0.0 / 0.0);
System.out.println(-1.0 / 0.0);

yields

Infinity
NaN
-Infinity

... which is, after all, the correct result, right? Introducing an inaccuracy will just bite you in an entirely different, unexpected way. Don't do it.