Categories
programming

Not All Divisions Are Equal

If you don’t need to pay attention to a particular detail every day, it can sneakily bite you in the derriere. Division is one of N culprits floating around the programmer’s haven. And this little guy thrives on C# .NET code.

Let’s take something simple like

int a=9, b=0;
return (a/b);

You’re expecting something similar to a “can’t divide by zero exception”, right? And indeed you do get one. In fact, all good programming courses will teach you the following idiom:

int a=9, b=0;
return (0==b)?0:(a/b);

Which is to say; only divide by ‘b’ if i’t not zero otherwise return 0 (or any other logical value).

Back to the code; what happens if I change the type from int to a floating point (float or double)? Afterall, no self-respecting programmer would do any financial calculations using integers, right?

double a=9, b=0;
return (a/b);

Divide by zero exception?

Nope.

What?

This is not a divide by zero exception condition. In fact, dividing by 0.00000 (or even -0f, yes, that’s a minus floating point zero) is perfectly acceptable and does give you a result.

What?

Yes. As I mentioned above, this is one of those “stickies” that you don’t often pay attention to, but definitely mess with your fundamental assumptions about life and the universe when you not getting the results you expect.

For a little more history on the problem, you can always refer to WikiPedia.

Is all hope lost? No. Just be careful out there because programming _is_ hard (for this and countless other reasons).