Reputation: 38919
I read here that remquo
should return:
If successful, returns the floating-point remainder of the division
x/y
as defined in std::remainder, and a value whose sign is the sign ofx/y
and whose magnitude is congruent modulo 2n to the magnitude of the integral quotient ofx/y
, where n is an implementation-defined integer greater than or equal to 3.
Now clearly I've misunderstood all that techno-speak cause I thought that I was going to get back the fractional result of the division. Instead this operation:
int quot;
const float rem = remquo(7.0F, 4.0F, ");
Sets quot
to 2 and rem
to -1.0! I can see how that is valid because 4.0 * 2 = 8.0 and 7.0 - 8.0 = -1.0. But why are we using a quot
that will result in a negative rem
? Shouldn't I be getting back a quot
of 1 and a rem
of 3.0?
Upvotes: 0
Views: 295
Reputation: 80276
Since your question is about the value returned by remquo
, it is entirely about std::remainder
, since that part of remquo
's behavior is defined directly as identical to that of std::remainder
.
std::remainder
provides the IEEE 754 remainder operation, which is different from fmod
in that the fmod
of two positive values can be expected to be always positive, whereas the IEEE 754 remainder is defined with respect to the integral quotient q
as the nearest integer to the mathematical quotient x/y, so that remainder = x - y*q
produces a negative result each time the mathematical quotient rounds up to the next integer.
The IEEE 754 remainder operation is the one being discussed in the question “Math.IEEERemainder returns negative results.” so you might want to read it and the accepted answer although they are about a different programming language.
Note: the part of the specification about the quotient being “congruent modulo 2n to the magnitude of the integral quotient” simply means that you do not get the entire integral quotient, which indeed might not fit an int
type (think of remquo(FLT_MAX, 1.0f, ...)
. Instead, you get an implementation-defined number of the least significant bits of the integral quotient. The implementation-defined number of bits that you get must be at least three, but can be more.
Upvotes: 1
Reputation: 313
The behavior is correct; as stated in std::remainder, the quotient is rounded to nearest integer, then the remainder could be negative.
If you are working with integer, I suggest you the C function div()
Upvotes: 1