Could someone please explain how the functions std::fmod and std::remainder work. In the case of the std::fmod
, can someone explain the steps to show how:
std::fmod(+5.1, +3.0) = 2.1
Same thing goes for std::remainder
which can produce negative results.
std::remainder(+5.1, +3.0) = -0.9
std::remainder(-5.1, +3.0) = 0.9
As the reference states for std::fmod:
The floating-point remainder of the division operation x/y
calculated by this function is exactly the value x - n*y
, where n
is x/y
with its fractional part truncated.
The returned value has the same sign as x
and is less than y
in magnitude.
So to take the example in the question, when x = +5.1
and y = +3.0
,
x/y
(5.1/3.0 = 1.7)
with its fractional part truncated is 1. So n
is 1
. So the fmod
will yield x - 1*y
which is 5.1 - 1 * 3.0
which is 5.1 - 3.0
which is 2.1
.
And the reference states for std::remainder:
The IEEE floating-point remainder of the division operation x/y
calculated by this function is exactly the value x - n*y
, where the value n is the integral value nearest the exact value x/y
. When |n-x/y| = ½
, the value n
is chosen to be even.
So to take the example in the question, when x = +5.1
and y = +3.0
The nearest integral value to x/y (1.7)
is 2
. So n
is 2
. So the remainder
will yield x - 2y
which is 5.1 - 2 * 3.0 which is 5.1 - 6.0
which is -0.9
.
But when x = -5.1
and y = +3.0
The nearest integral value to x/y (-1.7)
is -2
. So n
is -2
. So the remainder
will yield x - 2y
which is -5.1 - (-2) * 3.0
which is -5.1 + 6.0
which is +0.9
The reference also states that: In contrast to std::fmod()
, the returned value is not guaranteed to have the same sign as x
.
For those who may have a small difficulty understanding the good example by P.W., here is a slightly less mathematical approach.
fmod()
function tells you how much remains after dividing your numerator evenly by your denominator.
remainder()
function tells you how far your numerator is from the next closest number the denominator evenly divides into.
Examples:
fmod(10,3.5)
= 3
.
3.5
can fit twice into 10
(2*3.5 = 7
), leaving a remainder of 3
.
remainder(10,3.5)
= -0.5
.
3.5
cannot fit evenly into 10
, but it can fit evenly into 7
(2*3.5
) and 10.5
(3*3.5
).
10.5
is closer to 10
than 7
.
How far away is 10
from 10.5
?
It is -0.5
away from 10.5
.
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