I have a double[]
on which a LINQ operation is being performed:
MD = MD.Select(n => n * 100 / MD.Sum()).ToArray();
In some cases, all elements of MD
are 0 and then Sum
is also zero. Then 0 * 100 = 0 / 0
, but it is not giving a divide-by-zero exception or any exception. Why is this so?
Any number divided by zero gives the answer “equal to infinity.” Unfortunately, no data structure in the world of programming can store an infinite amount of data. Hence, if any number is divided by zero, we get the arithmetic exception .
As much as we would like to have an answer for "what's 1 divided by 0?" it's sadly impossible to have an answer. The reason, in short, is that whatever we may answer, we will then have to agree that that answer times 0 equals to 1, and that cannot be true, because anything times 0 is 0. Created by Sal Khan.
The Python "ZeroDivisionError: float division by zero" occurs when we try to divide a floating-point number by 0 . To solve the error, use an if statement to check if the number you are dividing by is not zero, or handle the error in a try/except block.
Try this:
double x = 0.0; double y = 1.0; double z = y / x;
That won't throw an exception either: it'll leave z
as positive infinity. There's nothing LINQ-specific here - it's just IEEE-754 floating point arithmetic behaviour.
In your case, you're dividing zero by zero, so you end up with not-a-number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With