I'm following an example where the fellow wants to generate a random number between 1 and 100.
targetValue= 1 + Int(arc4random_uniform(100))
He then states:
You are also calling the function arc4random_uniform() to deliver an arbitrary integer (whole number) between 0 and 100. Actually, the highest number you will get is 99 because arc4random_uniform() treats the upper limit as exclusive. It only goes up-to 100, not up-to-and-including. To get a number that is truly in the range 1 - 100, you need to add 1 to the result of arc4random_uniform().
I would not have guessed that, so I've searched on the Apple Developer site for documentation on this function. For the life of me I can't find it. Can someone point me to it?
Top search result on Google for me when searching "arc4random_uniform": arc4random_uniform(3). This is the same documentation available by running man 3 arc4random_uniform in the terminal.
The relevant parts:
u_int32_t arc4random_uniform(u_int32_t upper_bound);
arc4random_uniform()will return a uniformly distributed random number less thanupper_bound.arc4random_uniform()is recommended over constructions likearc4random() % upper_boundas it avoids "modulo bias" when the upper bound is not a power of two.
As documented, the upper bound is exclusive, so if you want to include the upper bound, you will need to either increase the bound, or shift the result up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With