Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why [float.MaxValue == float.MaxValue + 1] does return true?

I wonder if you could explain the Overflow in floating-point types.

float.MaxValue == float.MaxValue + 1 // returns true 
like image 584
Homam Avatar asked Nov 22 '10 23:11

Homam


People also ask

What is float MaxValue?

Represents the largest possible value of Single. This field is constant. public: float MaxValue = 3.40282347E+38; C# Copy.


2 Answers

Because the 1 is way too small to make a dent in the float.MaxValue value.

Anything less than 1e32 will fall below the precision of the float, so it's in effect the same as adding a zero.

Edit:

ulrichb showed that a value of 1e23 does actually affect float.MaxValue, which has to mean that you are not comparing floats at all, but doubles. The compiler converts all values to doubles before adding and comparing.

like image 195
Guffa Avatar answered Oct 17 '22 07:10

Guffa


That's very interesting:

float fMax = float.MaxValue; double dMax = double.MaxValue;  Console.WriteLine("{0}, {1}", fMax == fMax + 1E22f, fMax + 1E22f); Console.WriteLine("{0}, {1}", fMax == fMax + 1E23f, fMax + 1E23f);  Console.WriteLine("{0}, {1}", dMax == dMax + 1E291d, dMax + 1E291d); Console.WriteLine("{0}, {1}", dMax == dMax + 1E292d, dMax + 1E292d); 

prints:

 True, 3.402823E+38 False, 3.402823E+38 True, 1.79769313486232E+308 False, Infinity 

So, ... as Guffa noted fMax + 1E23f is converted to double and dMax + 1E292d adds up to Infinity.

like image 24
ulrichb Avatar answered Oct 17 '22 09:10

ulrichb