'Difference between c++ functions 'remainder' and 'fmod'?

Recently I came across the need to use fmod() function in C++ to calculate modulus of two long double operands.

But I also saw that there is some "remainder" function in C++ that does almost the same job.

What is the difference between those two functions?



Solution 1:[1]

The remainder() function in C++ computes the floating-point remainder of numerator/denominator (rounded to nearest).

remainder (x, y) = x - rquote * y

where rquote is the result of x/y, rounded towards the nearest integral value (with halfway cases rounded towards the even number).

Another hand, The fmod() function in C++ computes the floating-point remainder of numerator/denominator (rounded towards zero).

fmod (x, y) = x - tquote * y

where tquote is truncated i.e. (rounded towards zero) result of x/y.

Example

double x = 7.5, y = 2.1;
double result = remainder(x, y);// output is -0.9 
double result2 = fmod(x, y);// output is 1.2

Solution 2:[2]

From http://en.cppreference.com/w/cpp/numeric/math/remainder:

In contrast to std::fmod(), the returned value is not guaranteed to have the same sign as x.

Solution 3:[3]

fmod calculates as "These functions compute the remainder from the division of numerator by denominator. Specifically, the return value is numerator - n * denominator, where n is the quotient of numerator divided by denominator, rounded towards zero to an integer"

reminder calculates as "These functions are like fmod except that they round the internal quotient n to the nearest integer instead of towards zero to an integer"

Solution 4:[4]

Another way to put it:

std::remainder(x,y) will always return between [-y/2, y/2],

std::fmod(x,y) will return either [0, abs(y)] or [-abs(y), 0], depends on the sign of x.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Greg Hewgill
Solution 3 Naresh
Solution 4 auzn