Divide By Zero Oddities

c#

Solution

Can't quite get the debugger to display the NaN, but I'm just wondering why there is no error thrown in this case?

Because that would violate the specification :) Basically, there's no need to throw an exception here because IEEE-754 a) defines how division by 0 should be handled; b) has appropriate values for the results of division by 0. Neither of these is true for integer types (and `decimal`), which is where you get `DivideByZeroException`.

If you divide any non-zero, non-NaN value by zero, you should get infinity (positive or negative). If you divide zero (or NaN) by zero, you should get NaN.

Sample code:

using System;

class Test
{
    static void Main()
    {
        // Prevent everything being computed at compile-time
        double zero = 0d;
        Console.WriteLine(1d / zero);  // Infinity
        Console.WriteLine(0d / zero);  // NaN
        Console.WriteLine(-1d / zero); // -Infinity
    }
}

From the C# 5 specification section 7.8.2 (other numbering applies to other versions):

Integer division

[...] If the value of the right operand is zero, a System.DivideByZeroException is thrown. [...]

Floating point division

The quotient is computed according to the rules of IEEE 754 arithmetic. The following table lists the results of all possible combinations of nonzero finite values, zeros, infinities, and NaN’s.

(There's then a table giving the same sort of results as I've described earlier.)

Problem

I ran into an issue today where I was accidentally dividing by zero, but no exception was being thrown. When I used the debugger I was seeing 'NaN' in the debugger. When I tried to recreate this scenario with NUnit, Assert says I'm returning 'Infinity'. Can't quite get the debugger to display the NaN, but I'm just wondering why there is no error thrown in this case?? It took me quite awhile to track this problem down and I would have assumed an exception should have been thrown? Here is the testing code: ``` public class DivideByZero { private int TotalQaOneToFour; private int TotalGrade = 10; public DivideByZero(int TotalQaOneToFour) { this.TotalQaOneToFour = TotalQaOneToFour; } public Double QualityReportAverageRounded { get { return Math.Round((double)TotalGrade / TotalQaOneToFour, 2); } } } [TestFixture] public class DivideByZeroTest { [Test] public void TestThatDivideByZeroThrowsWhenUsingMathRound() { var dbz = new DivideByZero(0); Assert.AreEqual(0, dbz.QualityReportAverageRounded); } } ``` Here is the NUnit Output: Test 'DivideByZeroTest.TestThatDivideByZeroThrowsWhenUsingMathRound' failed: Expected: 0 But was: Infinity DivideByZero.cs(33,0): at DivideByZeroTest.TestThatDivideByZeroThrowsWhenUsingMathRound() 0 passed, 1 failed, 0 skipped, took 0.41 seconds (NUnit 2.6.1).

Original source

Related problems