Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

0 + 0 + 0... + 0 != 0

I have a program that is finding paths in a graph and outputting the cumulative weight. All of the edges in the graph have an individual weight of 0 to 100 in the form of a float with at most 2 decimal places.

On Windows/Visual Studio 2010, for a particular path consisting of edges with 0 weight, it outputs the correct total weight of 0. However on Linux/GCC the program is saying the path has a weight of 2.35503e-38. I have had plenty of experiences with crazy bugs caused by floats, but when would 0 + 0 ever equal anything other than 0?

The only thing I can think of that is causing this is the program does treat some of the weights as integers and uses implicit coercion to add them to the total. But 0 + 0.0f still equals 0.0f! As a quick fix I reduce the total to 0 when less then 0.00001 and that is sufficient for my needs, for now. But what vodoo causes this?

NOTE: I am 100% confident that none of the weights in the graph exceed the range I mentioned and that all of the weights in this particular path are all 0.

EDIT: To elaborate, I have tried both reading the weights from a file and setting them in the code manually as equal to 0.0f No other operation is being performed on them other than adding them to the total.

like image 386
Austin Henley Avatar asked Apr 24 '12 18:04

Austin Henley


People also ask

Why is 0 != 1 prove it?

If your definition is n! is the product of the nonnegative integers less than or equal to n, while your definition of "product" incorporates the convention "an empty product equals 1" then the proof of 0!= 1 is a two line proof applying the two lines of the definition, one by one.

Has 0 divided by 0 been solved?

So zero divided by zero is undefined.

Why is 0 raised to 0 not defined?

No value can be assigned to 0 to the power 0 without running into contradictions. Thus 0 to the power 0 is undefined!

Is 0 0 undefined or infinity?

Similarly, expressions like 0/0 are undefined. But the limit of some expressions may take such forms when the variable takes a certain value and these are called indeterminate. Thus 1/0 is not infinity and 0/0 is not indeterminate, since division by zero is not defined.


1 Answers

Because it's an IEEE floating point number, and it's not exactly equal to zero.

http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

like image 148
duffymo Avatar answered Oct 13 '22 13:10

duffymo