Is fmod() exact when y is an integer?
Solution 1:
The result of fmod
is always exact; whether y
is an integer is irrelevant. Of course, if x
and/or y
are already approximations of some real numbers a
and b
, then fmod(x,y)
is unlikely to be exactly equal to a mod b
.
Solution 2:
The IEEE Standard 754 defines the remainder operation x REM y
as the mathematical operation x - (round(x/y)*y)
. The result is exact by definition, even when the intermediate operations x/y
, round(x/y)
, etc. have inexact representations.
As pointed out by aka.nice, the definition above matches the library function remainder
in libm
. fmod
is defined in a different way, requiring that the result has the same sign as x
. However, since the difference between fmod
and remainder
is either 0
or y
, I believe that this still explains why the result is exact.