-1

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

Costa
  • 3,897
  • 13
  • 48
  • 81
  • 12
    This is how IEEE floating-point math works: this is consistent across the majority of the world's programming languages. Various well-defined operations can result in positive/negative infinity or NaN, and the results of performing further operations on these values are also well-defined. This article is required reading for all computer scientists: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – canton7 Dec 21 '21 at 16:21
  • 1
    This question doesn't appear to contain any questions. – Liam Dec 21 '21 at 16:32
  • 4
    `This is because there is nothing really called infinity in computer science` Wrong. [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) was introduced in 1985 and contains not just infinites but Not-a-Number, which you'll find in data science languages and libraries, like R and Python. – Panagiotis Kanavos Dec 21 '21 at 16:33

1 Answers1

4

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;

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215