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?
fmod() — Calculate Floating-Point Remainder The fmod() function calculates the floating-point remainder of x/y. The absolute value of the result is always less than the absolute value of y.
There is a difference between modulus and remainder. For example: -21 mod 4 is 3 because -21 + 4 x 6 is 3. But -21 divided by 4 gives -5 with a remainder of -1. For positive values, there is no difference.
In the C Programming Language, the fmod function returns the remainder when x is divided by y.
The remainder operator ( % ) returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With