possible bug in libgmp-4.3.2

Evan Teran eteran at alum.rit.edu
Mon Aug 23 21:45:31 CEST 2010


I recently came across an issue using kcalc which I tracked down to a
call in libgmp giving unexpected results.

Certain integer values yield incorrect results after "right shift"
operations. For example the following program:

--------------------------
#include <cmath>
#include <gmp.h>
#include <stdint.h>
#include <iostream>

int main() {
        const int64_t x = -214748339200000;

        mpz_t mpz;
        mpz_t result;
        mpz_init(mpz);
        mpz_init(result);

        mpz_set_si(mpz, x);
        mpz_tdiv_q_2exp(result, mpz, 32);

        const int64_t y = mpz_get_si(result);
        std::cout << y << std::endl;

        mpz_clear(mpz);
        mpz_clear(result);

        std::cout << (x >> 32) << std::endl;
}
--------------------------

outputs:
$ ./test
-49999
-50000

instead of the expected:
$ ./test
-50000
-50000

I found this surprising since there is no non-integer operations
involved meaning that I would not expect a loss of precision anywhere.
>From what I can tell mpz_tdiv_q_2exp is the correct operation to do
"right shifts" of integer values, but I am open to the possibility
that this is a gcc miscompilation since I am using gcc-4.5.1on an
x86_64 linux system.

However, it may also be a genuine bug so I thought I would bring it to
your attention. Please let me know if there is anything else I can do
to help track down the source of this issue.

Thank you,
Evan Teran


More information about the gmp-bugs mailing list