-3

I want to generate million of random numbers between 0 and 1 (0 and 1 included) using thread on POSIX. I try two codes but it still give me wrong results, it generate large signed numbers.

code(1):

srand(time(NULL));
for (i = 0; i < 10; i++)
{
   double r = (double)(rand()%1001)/1000;
  printf("Random double, 0 to 1: %f\n",r);
}

code(2):

srand(time(NULL));
for (i = 0; i < 10; i++)
{
   double r = rand()/(double)RAND_MAX;
   printf("Random double, 0 to 1: %f\n",r);
}

The results generated are like these:

12451421454

-4514251445

96541213212

-56543214521

SO what is the solution ,,,, please

Nano
  • 3
  • 4
  • The solution starts by telling us how a POSIX thread has *anything* to do with what little code you actually posted, followed shortly thereafter by posting a *real* [**MVCE**](http://stackoverflow.com/help/mcve). – WhozCraig Oct 19 '14 at 08:35
  • 3
    Looks fine here: http://ideone.com/23uQAG – Oliver Charlesworth Oct 19 '14 at 08:37
  • `printf("PI = %d\n",pi);` the `%d` format specifier prints one integer. Could you try to use `%f` or `%g` instead ? – francis Oct 19 '14 at 09:13
  • the problem begin before printf("PI = %d\n",pi); ,,, the values of x and y are NOT random numbers between 0 and 1 – Nano Oct 19 '14 at 09:18
  • They are. The code you **show** to generate x and y works as intended, and does not show the (integer) results you claim. Your error lies somewhere else--and it's *very* probable it's not even an actual error but you only used the wrong `printf` format somewhere. – Jongware Oct 19 '14 at 10:09

1 Answers1

2

Right ! The computed value of pi is not precise.

If you have 30 min, look at this video about generation of random number. Or this question C++ random float number generation.

x=(double)(rand()%1001)/1000; is not the right way to generate random numbers between 0 and 1...There are only 1000 possible values and some are more probable than others since RAND_MAX%1001!=0! x = rand()/(double)RAND_MAX; works better.

Moreover, remember the central limit theorem : the error goes like 1/sqrt(total) : you will never get 10 digits. Try to increase total.

And sqrt(x*x+y*y)<1 is costly : (x*x+y*y)<1 is sufficient.

Ultimately, try random of C++11.

srand(time(NULL)); may be a cause of trouble if you plan to use many threads : time(NULL) only changes once in a second, and many threads will get the same value. Send a seed to the thread or use a random_device to seed your random generator.

Community
  • 1
  • 1
francis
  • 9,525
  • 2
  • 25
  • 41
  • 1
    related: [Why do people say there is modulo bias when using a random number generator?](http://stackoverflow.com/q/10984974/4279) – jfs Oct 19 '14 at 17:14
  • [the last picture](https://www.wakari.io/sharing/bundle/jfs/Test%20PRNG%20using%20gray%20bitmap) illustrates the modulo bias issue. – jfs Oct 19 '14 at 17:19