From: Lawrence Kirby
Newsgroups: comp.lang.c
Subject: Re: why aren't my random numbers random ?
Date: Wed, 09 Jun 99 01:38:49 GMT
Message-ID: <928892329snz@genesis.demon.co.uk>

In article <7jm48e$606$1@eskinews.eskimo.com> scs@eskimo.com "Steve Summit" writes:
...
> When N is close to RAND_MAX... about the
> only thing you can do is to call rand() multiple times,
> discarding certain values:
>
> [code omitted]

This is very similar to something I've posted a few times.

#include <stdlib.h>

int randnum(int range)
{
    int divisor = RAND_MAX / range;
    int threshold = RAND_MAX - RAND_MAX % range;
    int randval;

    while ((randval = rand()) >= threshold)
        ;

    return randval / divisor;
}

In theory this could loop indefinitely. However the chance of exiting the loop on each iteration is always greater than 0.5 and usually much closer to 1. Therefore the chances of the loop continuing become vanishingly small after relatively few iterations (after 100 iterations it is probably much less than 1 chance in 10^^30). This does assume however that rand() isn't severely broken i.e. that it doesn't churn out large groups of large numbers. However even poor PRNG algorithms don't tend to do that (which leaves a genuinely buggy implementation).

-- 
-----------------------------------------
Lawrence Kirby | fred@genesis.demon.co.uk
Wilts, England | 70734.126@compuserve.com
-----------------------------------------