Re: Best way to get a non-repeating random number?
Re: Best way to get a non-repeating random number?
- Subject: Re: Best way to get a non-repeating random number?
- From: Peter Castine <email@hidden>
- Date: Wed, 15 Apr 2009 18:34:43 +0200
On 14-Apr-2009, at 22:32, Ricky Sharp wrote:
Personally, for all things random, I now use the Mersenne Twister
algorithm.
Again, it depends for what. Mersenne is bursty: it precalcs a buffer
of 624 values at a time, then it just reads out a value (and performs
a little magic on it) for each function call. So you have 623 fast
function calls and the 624th call sits in a loop recalculating the
buffer. Not great for, say, a real time process. RT generally prefers
to have a constant processor load.
And it's probably overkill for OP.
For all rand() is a poor RNG, if used cautiously it might well be good
enough (and efficient enough) for the task at hand. Of course random()
is a better algorithm, but it has some overhead. I often prefer
Tausworthe 88 for an efficient RNG with good statistical properties,
although it's not in any of the standard libraries.
However, I would advise against rand() to get random numbers in the
range 0-9. The output will have a short cycle, as well bias. The low-
order bits of rand() are notoriously non-random. Better to calculate
rand()/(RAND_MAX/10 + 1).
This last point would not be a problem with random() or other better
quality RNG.
On 14-Apr-2009, at 22:32, Eric E. Dolecki wrote:
int result = (arc4random()%9) + 1;
if (result >= activeTarget) ++result;
activeTarget = result;
That seems a little odd to me to do things that way - but I'm not
really
sure.
This will give you biased results. Instead of equally distributed
values in {1, 2,.. 10}, you will only get 10 just over 1.2% of the
time and 1 a bit under the expected 10%, with the other values taking
up the slack. Additionally, the absolute differences of consecutive
values will not be equally distributed. There will be a skew towards
sequences where x(n+1) = x(n) + 1. The second point may or may not be
a problem for a game whereas the first point is probably too deadly
even for a game.
The following would deal with the first point:
int result = myRandomNumberGenerator() % 10 + 1;
if (result == activeTarget)
result = result % 10 + 1;
activeTarget = result;
-- Peter
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden