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

后端 未结 5 1298
太阳男子
太阳男子 2020-12-06 09:07

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

float.MaxValue == float.MaxValue + 1 // returns true
相关标签:
5条回答
  • 2020-12-06 09:38

    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.

    0 讨论(0)
  • 2020-12-06 09:41

    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.

    0 讨论(0)
  • 2020-12-06 09:44

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

    0 讨论(0)
  • 2020-12-06 09:45

    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.

    0 讨论(0)
  • 2020-12-06 10:03

    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.

    0 讨论(0)
提交回复
热议问题