Why is arc4random returning outlandish values?

I call arc4random in a function in an iOS application to generate random values ​​from -5 to 6.

double num;
for (int i = 0; i < 3; i++) {
    num = (arc4random() % 11) - 5;
    NSLog(@"%0.0f", num);
}

I get the following output from the console.

2012-05-01 20:25:41.120 Project32[8331:fb03] 0
2012-05-01 20:25:41.121 Project32[8331:fb03] 1
2012-05-01 20:25:41.122 Project32[8331:fb03] 4294967295

0 and 1 are values ​​within the range, but wowww, where does 4294967295 come from?

Changing arc4random()to rand()fixes the problem, but of rand()course requires sowing.

+3
source share
2 answers

arc4random()returns a u_int32_tis an unsigned integer that does not represent negative values. Each time arc4random() % 11a number 0 ≀ n <5 appears, you subtract 5 and wrap them with a very large number.

double , , double, . :

 num = (double)(arc4random() % 11) - 5;

, .

+7

arc4random_uniform(11) - 5;

.

man:

arc4random_uniform() will return a uniformly distributed random number
 less than upper_bound.  arc4random_uniform() is recommended over con-
 structions like ``arc4random() % upper_bound'' as it avoids "modulo bias"
 when the upper bound is not a power of two.
+4

All Articles