one of the solutions given at
http://stackoverflow.com/questions/137783/given-a-function-which-produces-a-random-integer-in-the-range-1-to-5-write-a-fun
is:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int i;
do
{
  i = 5 * (rand5() - 1) + rand5();  // i is now uniformly random
between 1 and 25
} while(i > 21);
// i is now uniformly random between 1 and 21
return i % 7 + 1;  // result is now uniformly random between 1 and 7
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Why do we need to go for all this trouble??


Why not:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int i;
do
{
  i = rand5()  + rand5();  // i is now uniformly random between 1 and
10
} while(i > 7);
// i is now uniformly random between 1 and 7
return i;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Whats wrong with it??



On Sep 9, 12:34 am, Ramaswamy R <ramaswam...@gmail.com> wrote:
> Generate the random number 7 times. Sum them all and divide by 5.
> Theoritically it should be evenly distributed over 1-7. But owing to random
> number generators characteristics the sum of rand(5) called 7 times may not
> be perfectly evenly distributed over 1-7.
> A nice discussion on some neat options is available here 
> -http://stackoverflow.com/questions/137783/given-a-function-which-prod...
>
> Rejection technique is pretty standard for this and yet simple.
>
> On Mon, Sep 7, 2009 at 8:56 AM, ankur aggarwal 
> <ankur.mast....@gmail.com>wrote:
>
> >  Given a random number generator that generates numbers in the range 1 to
> > 5, how can u create a random number generator to generate numbers in the
> > range 1 to 7. (remember that the generated random numbers should follow a
> > uniform distribution in the corresponding range)
>
> --
> Yesterday is History.
> Tomorrow is a Mystery.
> Today is a Gift! That is why it is called the Present :).
>
> http://sites.google.com/site/ramaswamyr

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algogeeks@googlegroups.com
To unsubscribe from this group, send email to 
algogeeks+unsubscr...@googlegroups.com
For more options, visit this group at http://groups.google.com/group/algogeeks
-~----------~----~----~----~------~----~------~--~---

Reply via email to