Kyle Wheeler <kyle-wcalc-yahoo@...> schrieb:
>> + // a % b == a - floor(a/b) * b
>> + mpfr_div(output, first, second, GMP_RNDN);
>> + mpfr_floor(output, output);
>> + mpfr_mul(output, output, second, GMP_RNDN);
>> mpfr_sub(output, first, output, GMP_RNDN);
>
> Hmm. What is currently in CVS is this:
>
> mpfr_set_ui(temp, 0, GMP_RNDN);
> mpfr_div(temp, first, second, GMP_RNDN);
> mpfr_rint(temp, temp, GMP_RNDZ);
> mpfr_mul(output, temp, second, GMP_RNDN);
> mpfr_sub(output, first, output, GMP_RNDN);
What's the first line good for?
> Although after reading about it, I'm not sure. So, the problem is how
> to deal with negative numbers. For example, should -340 % 60 be -40
> or -20?
-20 is not an option. The question is: When performing the integer
division of -340 and 60, do you round the result by discarding the
fractional part (-5, leaving you with a remainder of -40) or by picking
the next-lower integer number (-6, leaving you with a remainder of
+20). It's getting even more complicated if the divisor is negative:
340/-60 could be either -5 (remainder 40) or -6 (remainder -20).
So, unless both the dividend and the divisor are positive we have to
pick one of two equally valid modulo results (one positive, one
negative). We have four possible ways to do this:
1. Always use the positive one; that's what my algorithm does:
-340 % 60 == 20; 340 % -60 == 40; -340 % -60 == 20
2. Use the one that's got the same sign as the dividend; that's what
your algorithm does and what the C99 standard requires:
-340 % 60 == -40; 340 % -60 == 40; -340 % -60 == -40
3. Use the one that's got the same sign as the divisor, always leaving
you with a modulo result between 0 and the divisor:
-340 % 60 == 20; 340 % -60 == -20; -340 % -60 == -40
4. Use the sign of the quotient, i.e. give the negative result if
either the dividend and the divisor are negative, and use the
positive result in case both are:
-340 % 60 == -40; 340 % -60 == -20; -340 % -60 == 20
I like the fourth solution, but I'm not yet sure how to implement it
most simple. If we want to be C99 conformant, we should stick with your
solution.
Cheers,
Ingo