weird results about integer division
jack dang
jacdang at gmail.com
Tue Feb 9 12:08:01 CET 2010
*GMP 5.0.1*
*No particular configure options are used other than ./configure*
*gcc version 4.3.2
Linux 2.6.27.5-117.fc10.i686 #1 SMP*
*Test code*
*#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
main()
{
mpz_t integ;
mpz_t mask;
mpz_t temp[25];
int i;
mpz_init (integ);
mpz_init (mask);
for(i = 0; i < 25; i++)
mpz_init (temp[i]);
mpz_set_ui (mask, 0x01f);
for(i = 1; i < 25; i++)
{
mpz_add_ui(integ, integ,i);
mpz_mul_2exp(integ, integ, 5);
}
mpz_add_ui(integ, integ, i);
for(i = 0; i < 25; i++)
{
mpz_and(temp[i], integ, mask);
mpz_tdiv_q_2exp(integ, integ, 5); // use tdiv_ or
fdiv_, but cdiv will cause wrong results
}
for(i = 0; i < 25; i++)
{
mpz_get_ui(temp[i]);
mpz_out_str(NULL, 10, temp[i]);
printf(" ");
}
printf("\n");
mpz_clear(integ);
mpz_clear(mask);
}*
The program is to store integers 0 ~ 25, five bits for each number, in a
128-bit integer. Then print them out.
However, if function *mpz_cdiv_q_2exp()* were used instead of *
mpz_fdiv_q_2exp()* or *mpz_tdiv_q_2exp()*, the results would be
25 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9
8 7 6 5 4 3 2
I am not familiar with rounding modes, and don't know how this was
implemented in the library. Guess might be a bug or I misused the library
in some way.
The expected result is
25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8
7 6 5 4 3 2 1
Just compile the program as following
gcc test.c -lgmp -o test
--
Wei Dang
More information about the gmp-bugs
mailing list