rondino - 7 months ago 53

C Question

Reading the answer of @anton in this link I tried to see if really

`remainder(x, y)`

`x-(round(x/y)*y)`

Running the code for the value of

`x=5.`

`y=2.`

`printf("the value of remainder is %f\n",remainder(x, y));`

printf("the value of remainder is %f\n",x-(round(x/y)*y));

the value of remainder is 1.000000

the value of remainder is -1.000000

From wikipedia :

Floating pointremainder. This is not like a normal modulo operation,

it can be negative for two positive numbers. Itreturns the exact

value of x–(round(x/y)·y).

Is the explanation of Anton wrong, or am I missing something ?

Answer

There is a slight difference in what `remainder`

does. From the man page:

The remainder() function computes the remainder of dividing x by y. The return value is x-n*y, where n is the value x / y, rounded to the nearest integer.

If the absolute value of x-n*y is 0.5, n is chosen to be even.

So in the halfway case the rounding part performed by `remainder`

does not round away from zero, but instead rounds to the *nearest even number*.