Mail Archives: djgpp/1996/09/03/19:49:32
Jason Hoffoss (hoffo002 AT gold DOT tc DOT umn DOT edu) wrote:
<snip>
: will work good, and give you good numbers. If you want like a number
: from 1 to 100, however, doing random() % 100 + 1 isn't going to give
: you great results. Why? Lets look at the natural range of random().
: It's a number from 0 to 4294967296. As you can see, with a %100, your
: chances of getting a number from 0-95 is a little higher than your
: chances of a number from 96-99. Other mod values will give you
: different distributions. What I would recommend instead is something
: like so, which keeps the probability flat:
:
: int myrand(void)
: {
: int n;
:
: do
: {
: n = random() & 127;
: } while (n >= 100);
:
: return n;
: }
:
: This gets quite a bit more complex when you want to generalize it for
: any range, but this should point you in the right direction. If you
: can, limiting your ranges to powers of 2 is the best solution.
:
: -Jason
:
Here is another solution. IF meory serves, it comes from RC4 author.
// returns a random integer in range 0 <= X < sides
unsigned range(unsigned sides)
{
unsigned const div = ((unsigned)RAND_MAX+1) / sides;
unsigned result;
while ((result = rand() / div) == sides)
; // retry
return result;
}
--
============================================
Without my guitar, I am a poet without arms.
- Michael Bloomfield
============================================
- Raw text -