Re: [AD] rand() vs random() |
[ Thread Index |
Date Index
| More lists.liballeg.org/allegro-developers Archives
]
That happens because the randomness of rand in the high bits is a lot better
than the one in the low bits (I don't remember where, but I read about it
somewhere and that's why the % operation wasn't good for it)
In fact, the webpage recommended something like this:
double x = (double)rand() / (double)(RAND_MAX+1);
where x would be a number from [0 to 1)
from there if say you want an integer fom [10 to 20] you would just do
x = (x * (20 - 10 + 1)) + 10;
int y = (int)x;
and done, probably it is slower but in real life programs you don't usually
need to make lots of quick calls to rand
> > It's not ansi, and afaics it's not in mingw. I've noticed improved
> > results before with ((rand()<<16)+rand()), can you try this?
>
> No, unfortunately that doesn't help here..
> Instead, I've tried replacing rand() with (rand()>>16) and this improved
> randomness a lot. Can we always assume rand() to fill all 32 bits of an
int
> (or better, is RAND_MAX always the highest 32bit number)?
>