@Karthikeya: Doesn't rand() actually return numbers in the range 0 to
RANDMAX? Proceeding as if that is the case:

If N is much smaller than RANDMAX, the process probably works well
enough for most applications, but if you want numbers as good as the
numbers rand() generates, do the following:

int random(int N)
{
    int m = (RANDMAX / N) * N
    while(1)
    {
        k = rand();
        if( k < m ) break;
    }
    return k % N + 1;
}

This rejects the values of rand() that would skew the result. In your
example, m = 30, so if rand() generates a number greater than or equal
to 30, rand() is called again. The loop terminates with probability 1
if rand() truly generates uniformly distributed numbers between 0 and
RANDMAX. The average number of calls is

ceiling((double)RANDMAX / (double)((int)(RANDMAX/N)*N)),

so in your example, it would be 50/30 = 5/3.

Dave

On Feb 26, 10:10 am, karthikeya s <[email protected]> wrote:
> RAND() func  returns value between 1 to INTMAX, as we know. But when
> smone tries to find out value between 1 to N he takes remainder of o/p
> of RAND() with N and adds one......but isn't it wrong coz RAND() will
> generate numbers with equal probability between 1 and INTMAX but
> taking remainder can alter the prob. of generating numbers.....
> e.g.
>
> INTMAX=50
> N=30
> RAND(50) gives numbers 1 to 30, then prob. will remain same but if it
> gives numbers 31 to 50, they'll be mapped to the numbers 1 to 20,
> which means probability of getting numbers 1 to 20 is more than the
> probability for 21 to 30.

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to