Search code examples
c#.netdivide-by-zero

Why does .Net return infinity?


This does not make any sense. In case of overflow or divide by zero, .NET should throw an exception or at least return an error code or bool (like TryParse). I think many would agree that it is difficult to anticipate that a framework would return infinity. This is because there is nothing really called infinity in computer science (How it will be represented in memory!). Furthermore, I cannot really do anything with it, I cannot use it as an input in another equation. This problem happened due to a bug that result in calling Math.Log(0).

What do I miss here?

https://learn.microsoft.com/en-us/dotnet/api/system.double.isinfinity?view=net-6.0


Solution

  • You have 2 different cases:

    1. When result is some kind of integer or decimal, DivideByZeroException exception will be thrown:

    The exception that is thrown when there is an attempt to divide an integral or Decimal value by zero. (bold is mine)

    // DivideByZeroException
    long v = 123L / 0L;
    
    // DivideByZeroException
    decimal d = 456m / 0m;
    
    1. When result is some kind of floating point, no exception will be thrown and there are 3 possible outcomes: +Inf, NaN, -Inf:
    // Positive Infinity
    double Positive = 123.0 / 0.0;
    
    // NAN - Not A Number
    double NotNumber = 0.0 / 0.0;
    
    // Negative Infinity
    double Negative = -456.78 / 0.0;
    

    In case of Math.Log() we deal with floating point values (double) for both argument and result, that's why

     Math.Log(0.0) == double.NegativeInfinity
    

    Note as well

     Math.Log(-1.0) == double.NaN
    

    is quite natural implementation;