tags:

views:

149

answers:

3

Hi all,

By design, why does the C# compiler allows any float or double values to be divided by zero?

class Program
{
    static void Main(string[] args)
    {
        double x = 0.0 / 0;

        float y = 1f / 0;


    }
}
+10  A: 

Because IEEE 754 floating-point values have special non-numeric values to deal with this:

PS Home:\> 1.0/0
Infinity
PS Home:\> 0.0/0
NaN

whereas dividing an integer by zero is always an exception (in the C# sense1), so you could just throw the exception directly.


1 Dividing a floating-point number by zero is also an exception but at a completely different level and many programming languages abstract this away.

Joey
Btw. 1/0 == Infinity is mathematical nonsense.
Luther Blissett
@Luther: lim_(n->\infty) 1/n goes towards it, though. Of course, it's not an actual number in mathematics as well.
Joey
1/x has a left and a right limit: `lim_(x->0+) 1/x = inf` but `lim_(x->0-) 1/x = -inf`. If the division behavior was defined using limits, then 0/0 should be 0 (not nan), because `lim_(x->0) 0/x = 0`. Never trust your FPU
Luther Blissett
+1  A: 

Because floating point values have a valid (and genuinely useful) representation of infinity, whereas integers of any type do not.

Drew Hall
A: 

The reason the compiler allows you to divide a float or a double by zero, is that float and double have representations on the notion of positive infinity and negative infinity (and "not a number"), so it is a meaningful thing to allow.

One oddity is that the compiler fails spot

 decimal d = 2; 
 decimal d2 = d/0M

as a divide by zero, even though it does spot it if you write the equivalent code for an integer.

Rob Levine
That's not true, division by zero on a `decimal` throws a `DivideByZeroException`, and the code `decimal d = 1.0M / 0.0M` will not even compile ("Division by constant 0").-.
0xA3
@0xa3, excluding decimal.
xport
@0xA3 - maybe, and yet decimal d = 2; decimal d2 = d/0M; does compile, even though the equivalent with integers does not.
Rob Levine
@Rob Levine: My point was that your last paragraph doesn't make sense because division by zero is not a valid operation on the `decimal` type. It either does not compile or throws a runtime exception.
0xA3
@Rob: That's likely an artifact of what the compiler optimizes immediately.
Joey
@0xA3 - I think maybe you misunderstood what I was saying in my last paragraph. Obviously it isn't actually a valid operation for a decimal - I'm not trying to suggest it is. My point was that given this fact, you might expect the compiler to not allow such an obvious case, as indeed it doesn't for an integer. To rephrase my last sentence: "Given the compiler can detect this invalid operation at *compile time* for an integer, it is perhaps suprising it doesn't do the same for the decimal"
Rob Levine