How can I check if a double x is evenly divisible by another double y in C? With integers I would just use modulo, but what would be the correct/best way to do it with doubl
The standard header math.h
defines the following functions:
double fmod(double x, double y);
float fmodf(float x, float y);
long double fmodl(long double x, long double y);
These functions return the result of the remainder of x
divided by y
. The result has the same sign as that of x
. You can use r = fmod(x, y);
for double
numbers x
and y
, and check if r == 0
. If you want to not test for exact divisibility but add some tolerance, then you can check if r
is "close enough" to 0 or y
(thanks caf).
fmodf()
and fmodl()
are new in C99.
Edit: C99 also defines a separate remainder(double x, double y)
function, that returns the remainder of x/y
. From http://docs.sun.com/source/806-3568/ncg_lib.html:
The
remainder(x,y)
is the operation specified in IEEE Standard 754-1985. The difference betweenremainder(x,y)
andfmod(x,y)
is that the sign of the result returned byremainder(x,y)
might not agree with the sign of eitherx
ory
, whereasfmod(x,y)
always returns a result whose sign agrees withx
. Both functions return exact results and do not generate inexact exceptions.
...
When
y
≠ 0, the remainderr = x REM y
is defined regardless of the rounding mode by the mathematical relationr = x - ny
, wheren
is the integer nearest the exact value ofx/y
; whenever| n - x/y | = 1/2
, thenn
is even. Thus, the remainder is always exact. Ifr = 0
, its sign shall be that ofx
. This definition is applicable for all implementations.
(Either fmod()
or remainder()
should work for you.)