Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arc4random Random Number Generator

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?

like image 466
Linuxmint Avatar asked Nov 28 '22 10:11

Linuxmint


1 Answers

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.)

like image 106
Chris Jester-Young Avatar answered Dec 09 '22 09:12

Chris Jester-Young