Uniform random number is not Uniform!!!
Gerrit
loki at hot.a2000.nl
Sat Dec 16 01:27:02 CET 2006
rohan <rohan076 <at> gmail.com> writes:
>
>
> I used the unsigned long mpz_urandomm(ran, s, N) function to generate a
> random number. the documentation says that the number generated will be
> uniformly distributed between 0 and n-1 inclusive!!! but after running the
> program several times i realised that for smaller N's the random numbers are
> better distributed in the range 0 to n-1
> I wrote this small piece of code, it basically generates random numbers from
> 0 to n-1, where n = z^ex
> ---------------------
> #include <stdio.h>
> #include <gmp.h>
>
> int main(void) {
> gmp_randstate_t s;
> unsigned long seed, i, z,ex;
> mpz_t big;
> mpz_init(big);
> mpz_t store;
> ex = 10;
> z=2;
> mpz_ui_pow_ui(big, z, ex);
> gmp_printf("BIG : %Zd", big);
> gmp_randinit_default(s);
> seed = time(NULL); // system time
> gmp_randseed_ui(s, seed);
> for(i = 0; i < 50; ++i) {
> mpz_init(store);
> mpz_urandomm (store, s, big);
> gmp_printf("\nRAN : %Zd", store);
> }
> gmp_randclear(s);
> return 0;
> }
> -------------------------------------------------------
> now the random numbers were evenly distributed for ex=10, but for ex = 256,
> the random numbers generated were mostly in the range on 2^240 to 2^256 ,
> how can this be called evenly distributed?? am I missing something or this
> has something to do with the seed value.
> Help is appreciated! Thanks in advance.
Yes, you're missing something, I'm afraid. You should realize that most numbers
can indeed be found in the range you mention. Why is that? Have a look at this
table:
2^1 - 2^0 = 1
2^2 - 2^1 = 2
2^3 - 2^2 = 4
...
2^11 - 2^10 = 1024 etc.
As you can see, the difference between powers of 2 is doubled all the time.
That's why chances are slim you will get results below 2^240, because (2^240 -
2^0) is far less than (2^256 - 2^240).
Gerrit
More information about the gmp-discuss
mailing list