mpz_rrandomb most significant bit always set

Emmanuel Thomé emmanuel.thome at gmail.com
Fri Mar 4 13:37:15 UTC 2016


Hi,

The documentation of mpz_rrandomb says:

 -- Function: void mpz_rrandomb (mpz_t ROP, gmp_randstate_t STATE,
          mp_bitcnt_t N)
     Generate a random integer with long strings of zeros and ones in
     the binary representation.  Useful for testing functions and
     algorithms, since this kind of random numbers have proven to be
     more likely to trigger corner-case bugs.  The random number will
     be in the range 0 to 2^N-1, inclusive.

I was surprised to notice that in fact, the most significant bit of
the output seems to be always set, as shown by the code below.

Sure, this behaviour does not *contradict* the documentation, but
perhaps the latter could be changed to reflect this fact, as for
example in:
     The random number will be in the range 2^(N-1) to 2^N-1, inclusive.

Best,

E.

#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>

int main(int argc, char * argv[])
{
    mpz_t x;
    gmp_randstate_t state;
    mpz_init(x);
    gmp_randinit_default(state);
    int iter = (argc > 1) ? (atoi(argv[1])) : 100;
    for(int i = 0 ; i < iter ; i++) {
        mpz_rrandomb(x, state, 64);
        printf("%d\n", mpz_tstbit(x, 63));
    }
    gmp_randclear(state);
    mpz_clear(x);
}

/*
 $ ./a.out 10000 | uniq -c
  10000 1
*/


More information about the gmp-discuss mailing list