-
problem in fmod()
Code:
cout << fmod(6.0*0.02, 0.02) << endl;
cout << fmod(6*0.02, 0.02) << endl;
cout << fmod(5.0*0.02,0.02) << endl;
cout << fmod(5*0.02,0.02) << endl;
cout << fmod(3.0*0.02,0.02) << endl;
cout << fmod(3*0.02,0.02) << endl;
(output)
0.02
0.02
3.46945e-018
3.46945e-018
0.02
0.02
The answers are supposed to be all zero.
I'm not sure why fmod() shows incorrect results for every multiple of 3 (3, 6, 9, ...)?
Does anyone have any idea?
Thanks.
-
fmod() is working correctly. What you're seeing has to do with binary floating-point being an inexact representation of decimal values.
Let's look at the first parameters to your fmod() calls (there are only three unique ones):
1) 6*0.02 : in decimal this is 0.12; in double-precision binary floating-point it's 0.119999999999999995559107901499373838305473327636 71875
2) 5*0.02 : in decimal this is 0.1; in double-precision binary floating-point it's 0.100000000000000005551115123125782702118158340454 1015625
3) 3*0.02 : in decimal this is 0.06; in double-precision binary floating-point it's 0.059999999999999997779553950749686919152736663818 35937
Now let's look at the second parameter, 0.02. In double-precision binary floating-point it's 0.020000000000000000416333634234433702658861875534 0576171875
(Sorry about the spaces inserted in my long decimal values -- that is formatting done by cboard that I can't control.)
If you perform fmod() on these actual values, your results make sense (although cout won't print them to the detail I've shown above -- see my article Print Precision of Dyadic Fractions Varies by Language - Exploring Binary).