Reputation: 41
I'm trying to obtain the remainder of two float numbers in C++ for some calculations and I found out that the built in std::remainder() function doesn't always return what I expect to.
For a concrete example, std::remainder(683.242, 27.8576183)
returns -13.1985
, instead of ~14.66
. I realized that -13.1985
is what you would have to add to 27... to obtain the correct remainder, which makes me suspect that -13... is the expected result and I'm missing something about what std::remainder() really does.
I'd be thankful if someone could tell me why std::remainder() returns negative values, or point me to some function / library that I can actually use to obtain 'normal' remainders from decimal numbers.
Upvotes: 0
Views: 506
Reputation: 1194
The floating-point remainder of the division operation x/y calculated by std::remainder(x,y)
is exactly the value x - n*y
, where the value n is the integral value nearest the exact value x/y. If |n-x/y| = 0.5 (precisely)
, the value n
is then chosen to be even.
So the returned value is not guaranteed to have the same sign as x.
If it rounds one way you get a positive number, if you round another you can get a negative one. Consider using std::fmod(...)
Upvotes: 1
Reputation: 41
Ok, this was short, but I found out that I'm, indeed, not supposed to use std::remainder() to get the remainder. The function that actually returns the mathematical 'normal' remainder is std::fmod() because reasons.
The reason std::remainder() doesn't work is because it rounds the quotient towards the nearest integer, as explained here. This also explains why the negative remainders I were getting were the difference between the divisor and the expected remainder.
Upvotes: 1