Sabashan Ragavan
Sabashan Ragavan

Reputation: 738

fmod function from math.h library in C not working correctly?

Ok, so hopefully I do not look like an idiot from asking this question...as it is quite basic, but my brain is either on vacation or something is indeed wrong.

So -4 % 5 or -4 mod 5 should equal 1 correct? Why is it that the fmod function from the math.h library returns -4 when you use it, i.e fmod(-4, 5) returns -4 instead of 1. I'm using the gcc compiler via cygqin if that is any help as well.

Thanks!

Upvotes: 0

Views: 2278

Answers (3)

Caio Monteiro
Caio Monteiro

Reputation: 1

Your compiler are using the following formula:

m = -4 - (Trunc(-4 / 5) * 5)
m = -4 - (Trunc(-0.8) * 5)
m = -4 - (0 * 5)
m = -4 - 0
m = -4

Instead of:

m = -4 - (Floor(-4 / 5) * 5)
m = -4 - (Floor(-0.8) * 5)
m = -4 - (-1 * 5)
m = -4 - (-5)
m = 1

Upvotes: 0

Yaakov
Yaakov

Reputation: 1703

POSIX states:

    #include <math.h>
    double fmod(double x, double y);

These functions shall return the value x - i * y, for some integer i such that, if y is non-zero, the result has the same sign as x and magnitude less than the magnitude of y.

In the case of fmod(-4,5), since the result must have the same size of x, it will be negative, and i cannot be less than zero. If i were to be one, the result would be larger than y, so i must be zero, and the result of -4.0 is correct.

Upvotes: 1

ldav1s
ldav1s

Reputation: 16315

The % operator is the remainder operator, not modulo. The fmod function is also the floating point remainder, not modulo. In this case, they have selected to round -4/5 toward 0 to an integer.

Upvotes: 4

Related Questions