Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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?

like image 713
mayank baiswar Avatar asked Sep 08 '14 22:09

mayank baiswar


People also ask

What is fmod function in C?

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.

What is difference between modulus and remainder?

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.

Is there a remainder function in C?

In the C Programming Language, the fmod function returns the remainder when x is divided by y.

What is the remainder command used for?

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.


1 Answers

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
like image 143
Arun Kumar Avatar answered Sep 24 '22 06:09

Arun Kumar