4
int randomNumber = (arc4random() % 83) + 1;

Is this the best way to generate "the most random" number? Or is there a better way to generate a random number?

Linuxmint
  • 4,716
  • 11
  • 44
  • 64
  • You can refer this question: http://stackoverflow.com/questions/3724526/how-to-generate-random-number-from-0-5-to-1-0/3724668#3724668 – Girish Kolari Dec 14 '10 at 05:19

3 Answers3

13

When you use arc4random you avoid one pitfall of using % with linear congruential generators (which is the usual algorithm used by rand): the low-order bits aren't less random.

However, you still have truncation issues: i.e., because (1 << 32) % 83 is 77, that means that numbers between 0 and 76 appear (slightly) more frequently than numbers between 77 and 82. To avoid this, you should throw away the incoming value (i.e., call arc4random again) if it's above (1 << 32) / 83 * 83.

(I assume the range of arc4random is from 0 to 232-1. Adjust the above explanation accordingly.)

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • 1
    @Joe Blow: The OP asked for the "best" random number generation system ordinarily available, so, I was answering to that. Also, `arc4random` is awesome: it uses kernel-collected entropy and all that good stuff. – C. K. Young Dec 14 '10 at 16:32
  • 1
    @Joe Blow: Actually, `arc4random` is crypto-grade randomness. It's equivalent to reading from `/dev/arandom`. So you could use it for crypto-grade stuff, if you handle the randomness correctly (and don't unwittingly skew the results by not doing the check I mentioned). – C. K. Young Dec 16 '10 at 01:40
  • There are now a number of well-known biases in arc4. For example, http://www.worldlingo.com/ma/enwiki/en/RC4 "The keystream generated by the RC4 is biased in varying degrees towards certain sequences." This is why you can't use arc4 for, for example, scientifically important MC sims. – Fattie Dec 16 '10 at 07:03
9

arc4random has a superior algorithm for generating random numbers based on the current time. There are other rand functions but they are not as good and require seeding.

prgmast3r
  • 413
  • 5
  • 8
2

The best random number generator I've ever seen (as well as a very clear definition of what random means) can be found in Stephen Wolfram's A New Kind of Science. He's been using a very simple cellular automata as his random number generator for decades in his Mathematica software program so it's been extremely well tested.

Brian Shriver
  • 267
  • 1
  • 4