Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "Divide by Zero" or any other exception not raised?

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?

like image 309
Nikhil Agrawal Avatar asked Apr 20 '12 08:04

Nikhil Agrawal


People also ask

What is the exception if you divide a number by zero?

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 .

Why is division by zero an error?

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.

How do you fix a zero division error?

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.


1 Answers

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.

like image 173
Jon Skeet Avatar answered Sep 17 '22 22:09

Jon Skeet