# What is the reason of inaccuracy of operations on float numbers?

I wonder why in JavaScript

0.1 + 0.2  // return 0.30000000000000004

4%0.1 // return 0.09999999999999978


http://jsbin.com/oHISAfU/1/edit (Example)

In C the math.h library fmod function

printf("%f", fmod(4.0,0.1));  // print 0.100000


http://ideone.com/RG5Wyv (Example)

And in Spotlight (search feature in the Mac OS X ~ I already submit bug report) that support math operation

4%0.1 = 0.1


• Recommended reading: floating-point-gui.de Commented Aug 19, 2013 at 9:59
• Another recommendation: Goldberg's What every computer scientist should know about floating point arithmetic. Commented Aug 19, 2013 at 13:16
• Not a recommendation, but there are infinitely many floating numbers, and only, say, $2^{32}$ binary numbers to represent them. Indeed, there are infinitely many rational numbers between 0 and 1, ($1/2, 1/3, 1/4, 1/5, \dots$) and therefore there must be some holes. Commented Aug 19, 2013 at 17:34

 printf("%.20f", fmod(4.0,0.1));

prints 0.09999999999999978351.
Ilmari Karonen gets it right in the other answer. But it gets even worse than that: arithmetic operations involving floating-point numbers don't necessarily behave the same as operators we're used to from mathematics. For instance, we're used to addition being associative, so that $a + (b + c) = (a + b) + c$. This doesn't generally hold using floating-point numbers, and for a given format it's not hard to come up with counterexamples. Not exactly relevant to the question you asked, except to illustrate that you should never assume floating point calculations are going to be exact.
• In particular, for sufficiently large $a$ and sufficiently small $b > 0$, it's quite possible that $a + b = a$ in floating point. Commented Aug 19, 2013 at 18:56