Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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://docs.microsoft.com/en-us/dotnet/api/system.double.isinfinity?view=net-6.0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

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

is quite natural implementation;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading