Search code examples
cmingwcodeblocksfloating-accuracy

Why 4.7 is 4.6999999 in c


'

#include <stdio.h>
#include <math.h>

int main(){  
        int i;  
        float num = 4.700;   
        for(i=1;i<5;i++){ 
              printf("%0.3f\tx%d\t\t=%d\n",num,(int)pow(10,i),(int)(num*pow(10,i)));
        }  
        return 0;
}

' This code prints the following to the console: '

4.7000   x10        =46  
4.7000   x100       =469  
4.7000   x1000      =4699  
4.7000   x10000     =46999

' This result is not consistent with all floating point values

1.2000 prints out ...120...1200 etc
1.8000 is strange again

I am working in Codeblocks and my question is why do some floats react this way?I there something fundamental to C or the mingw compiler that I am missing? Or is there something wrong with my code?
Thanks for the help and sorry if it's a repeat question


Solution

  • This is the nature of finite precision representations. When you try to use a number that cannot be represented exactly, this kind of thing will happen.

    The same thing happens with finite precision decimal. If you use six digits, you can only represent 1/3 as "0.333333". But now 3 times 1/3 is not going to be equal to one. And you can represent 2/3 as "0.666667", but now 1/3 times 2 is not going to equal 2/3.

    4.7 cannot be exactly represented in binary, just as 1/3 cannot be exactly represented in decimal. The closest possible representation is used, which is just slightly smaller.