GMP random number generation.

Sisyphus sisyphus1 at optusnet.com.au
Sun Mar 23 12:55:01 CET 2008


----- Original Message ----- 
From: "Mikhail Gorbachev" <gorbachevma at gmail.com>
To: <gmp-bugs at swox.com>
Sent: Friday, March 21, 2008 4:48 AM
Subject: GMP random number generation.


> Hi.
> I'm using GMP libriary to generate random numbers. I wrote this code
> //------------------------------------------------------------------------------------
> //...
>    mpz_t rand_Num;
>    gmp_randstate_t r_state;
>    mpz_init2(rand_Num,32);
>    gmp_randinit_default (r_state);
>    mpz_urandomb(rand_Num,r_state,14);
>    /* ...using generated random number...*/
>    gmp_randclear(r_state);
> //...
> //-------------------------------------------------------------------------------------
>
> However, I cannot get the random number. For each run of the program the
> result of this code is always rand_Num = 10356. When I change 14 to some
> other number, the value of rand_Num changes but always remains the same
> for the same number.
>
> I'm using the latest version of GMP libriary (4.2.2)
>
> Is there a bug here or I just do something wrong?

There's no bug.

Firstly, see 
http://gmplib.org/manual/Random-State-Seeding.html#Random-State-Seeding .

Consider the following:

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

int main (void) {
    mpz_t rand_Num;
    unsigned long int i, seed;
    gmp_randstate_t r_state;

    seed = 123456;

    gmp_randinit_default (r_state);
    gmp_randseed_ui(r_state, seed);

    mpz_init(rand_Num);

    for(i = 0; i < 10; ++i) {
       mpz_urandomb(rand_Num,r_state,14);
       gmp_printf("%Zd\n", rand_Num);
    }

    gmp_randclear(r_state);
    mpz_clear(rand_Num);
    return 0;
}
///////////////////////////////////////////////////////

Each time you run that you will get 10 (pseudo)random numbers output.
Each time you run it you will get the *same* 10 numbers output.
If you want different numbers each time you run the program, you will need 
to either:

1) Nominate a different range of values (by changing the "14" to something 
else ... as you've already discovered);
or
2) Change the value of the variable named "seed";
or
3) Choose a different initialization (as outlined at 
http://gmplib.org/manual/Random-State-Initialization.html#Random-State-Initialization ) 
.

Or you could use a combination of the above 3 options.

Cheers,
Rob 



More information about the gmp-bugs mailing list