3

Reading the answer of @anton in this link I tried to see if really remainder(x, y) is exactly x-(round(x/y)*y).

Running the code for the value of x=5. and y=2.. I got:

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 point remainder. This is not like a normal modulo operation, it can be negative for two positive numbers. It returns the exact value of x–(round(x/y)·y).

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

Community
  • 1
  • 1
rondino
  • 395
  • 2
  • 3
  • 10

1 Answers1

2

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • so I should use `nearbyint()` function instead ? – rondino Aug 03 '16 at 15:46
  • 1
    Good answer (+1). Might want to add in a link/reference to [banker's rounding](http://c2.com/cgi/wiki?BankersRounding) so OP can learn more about different rounding algorithms and their error bounds. :) – Cloud Aug 03 '16 at 15:46
  • I will check your answer if you provide a link for that ! – rondino Aug 03 '16 at 16:00
  • @rondino Added the link. Also changed quoted test as the wording differs from my local man page (the meaning is the same, though). – dbush Aug 03 '16 at 16:06