Why does C # allow dividing a nonzero number by zero in a floating point type?

Why C # allows you to:

1.0 / 0 // Infinity 

And does not allow:

 1 / 0 // Division by constant zero [Compile time error] 

Mathematically, are there differences between integers and floating point numbers when dividing by zero?

+47
floating-point c # divide-by-zero
Nov 23 '10 at 23:58
source share
4 answers

According to Microsoft, "floating point arithmetic overflow or division by zero never throws an exception because floating point types are based on IEEE 754 and therefore have provisions for representing infinity and NaN (not numbers)."

Read more about it here .

+46
Nov 24 '10 at 0:01
source share

Mathematically, there is no difference. However, with computers, only the standard IEEE-754 floating point specification has special values ​​for representing Β± ∞. Integers can only contain integers :-)

+13
Nov 24 '10 at 0:03
source share

The IEEE Floating Point Arithmetic Standard (IEEE 754) is the most widely used floating point standard, followed by many hardware and software implementations, including the C # compiler.

This means that a floating point variable in C # may contain a bit pattern representing strange creatures such as PositiveInfinity, NegativeInfinity and Not-a-Number (abbreviated as NaN). According to IEEE 754 arithmetic rules, any of these non-finite floating point values ​​can be generated by certain operations. For example, an invalid floating point operation, such as dividing zero by zero, results in NaN.

In your specific examples, you can see that C # (unlike VB) overloads the / operator to mean either integer or floating point division, depending on the number types of the numbers involved.

In the first example, the compiler sees 1.0 and therefore uses floating point division and transfers the result to a floating point variable. This variable contains a representation of infinity.

In the second example, the compiler sees 1 and therefore uses integer division and puts the result in an integer variable. Since integral types in C # use two complement systems to represent and do not use any special bit patterns to represent infinity (or NaN), the compiler gives an error.

There are other interesting subtleties with floating point . And it's worth reading Eric Lippert 's blog entry on this subject.

+8
Nov 24 '10 at 0:23
source share

Floating point division is supported by IEEE754, which indicates that division by zero should be infinite. There is no such standard for integer division, so they just went with standard math rules.

+6
Nov 24 '10 at 0:01
source share



All Articles