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

别等时光非礼了梦想. 提交于 2019-12-17 16:32:02

问题


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

float.MaxValue == float.MaxValue + 1 // returns true

回答1:


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.




回答2:


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.




回答3:


The problem here is floating point precision. float.MaxValue corresponds to 3.40282e+038f. But a float has much less precision that, in fact, there are only 7 digits of precision.

Anything beyond that precision is "filled with zeros", and adding 1 to that high number will not change it.




回答4:


Succinctly, the difference is in the 39th digit, and float only stores the first 7 (ish). This is a characteristic of floating-point arithmetic.




回答5:


To get a float type temporary variable to actually hold a single precision value, it must have been loaded from a float variable in memory. The compiler is generally allowed to represent single-precision values with more precision than required, and tends to do so while the value is in a register. When it spills back to memory the extra precision is lost.



来源:https://stackoverflow.com/questions/4251298/why-float-maxvalue-float-maxvalue-1-does-return-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!