nisse at lysator.liu.se
Mon Jun 24 21:24:44 CEST 2013
leif <not.really at online.de> writes:
> FWIW, in 5.1.1 there's
> /usr/include/gmp.h:#define mpz_div_2exp mpz_fdiv_q_2exp
Ah, there it is. And fdiv means floor, i.e, rounding towards -infinity,
*not* towards zero. It works as an arithmetic right shift, if one thinks
about negative numbers as using two's complement representation.
So, e.g, -5 (decimal) divided by 2 gives -3. In signed-magnitude binary,
-101 >> 1 == -11
which might look strange. But in two's complement (with infinitely many
ones to the left), it's
...11111011 >> 1 == ...11111101
which is a plain arithmetic right shift.
BTW, using >> in C for signed numbers is implementation defined, IIRC,
but at least on my platform it seems to be compiled to an arithmetic
right shift, i.e., rounding towards -infinity. Unlike the division
operator, which rounds towards zero. The following test program,
main (int argc, char **argv)
int x = -5;
printf ("%d >> 1 == %d\n", x, x >> 1);
printf ("%d / 2 == %d\n", x, x / 2);
-5 >> 1 == -3
-5 / 2 == -2
Not sure if this makes the GMP behaviour more or less confusing...
Niels Möller. PGP-encrypted email is preferred. Keyid C0B98E26.
Internet email is subject to wholesale government surveillance.
More information about the gmp-bugs