C- Floating point precision

后端 未结 4 1228
终归单人心
终归单人心 2020-11-28 16:25

I have a program:

int main() 
{   
        float f = 0.0f;  
        int i;  

        for (i = 0 ; i < 10 ; i++) 
                f = f + 0.1f; 

                


        
相关标签:
4条回答
  • 2020-11-28 16:51

    This is equivelent to adding 0.33 together 3 times (0.99) and wondering why it is not equal to 1.0.

    You may wish to read What Every Programmer Should Know About Floating Point Arithmetic

    0 讨论(0)
  • 2020-11-28 16:58

    Binary floating point cannot represent the value 0.1 exactly, because its binary expansion does not have a finite number of digits (in exactly the same way that the decimal expansion of 1/7 does not).

    The binary expansion of 0.1 is

    0.000110011001100110011001100...
    

    When truncated to IEEE-754 single precision, this is approximately 0.100000001490116119 in decimal. This means that each time you add the "nearly 0.1" value to your variable, you accumulate a small error - so the final value is slightly higher than 1.0.

    0 讨论(0)
  • 2020-11-28 17:04

    You cannot compare floats like this. You need to define a threshold and compare based on that. This blog post explains

    0 讨论(0)
  • 2020-11-28 17:07

    For floating point numbers you should always use an epsilon value when comparing them:

    #define EPSILON 0.00001f
    
    inline int floatsEqual(float f1, float f2)
    {
        return fabs(f1 - f2) < EPSILON; // or fabsf
    }
    
    0 讨论(0)
提交回复
热议问题