0

I found a strange results in the float assignment in CPU

My code is

float W[0]=0.1;
printf("%.10f",W[0]);

The result is 0.1000000015

Can anyone give me a help?

Thank you.

Sam Locus
  • 3
  • 3
  • I guess you are getting the machine epsilon: http://en.wikipedia.org/wiki/Machine_epsilon – Marcs Dec 02 '14 at 01:47
  • 1
    So, when you searched SO or the wider net for the terms `float inaccurate`, did you not see the billion and one posts _already_ detailing what you want to know? See http://powerfield-software.com/?p=30 for one of them. – paxdiablo Dec 02 '14 at 01:53
  • Use `double` if you need 10 accurate decimal digits – mukunda Dec 02 '14 at 02:04
  • 2
    possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – phuclv Dec 02 '14 at 02:42
  • 1
    float typically only has 6 digits of precision http://floating-point-gui.de/ – phuclv Dec 02 '14 at 02:43
  • The more verbose version: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). To be more precise, single precision float is accurate to about 6-7 digits – phuclv Dec 02 '14 at 07:55
  • https://home.comcast.net/~tom_forsyth/blog.wiki.html#[[A%20matter%20of%20precision]] is an excellent write up of why you shouldn't do what a lot of people are probably about to suggest ... doubles won't fix many problems here ... – Andy Newman Dec 02 '14 at 13:40

1 Answers1

0

0.1 decimal is a repeating 'bicimal': 0.0 0011 0011 0011 0011 0011 0011 0011 ... (the 0011 repeats, which I've shown with spaces). Rounded to 24 significant bits -- to fit into a float -- that is 0.000110011001100110011001101. That is 0.100000001490116119384765625 in decimal. Rounded to 10 places, the decimal number is 0.1000000015 .

Rick Regan
  • 3,407
  • 22
  • 28