Search code examples
objective-carc4randomunderflow

Why there is unexpected result in arc4random() % n?


i have

for (int i = 0; i< 10; i++) {
    CGFloat longerA = ((arc4random() % 80) - 40) / 100.0f;
    NSLog(@"%f",longerA);
}

and the result is

2013-09-20 11:41:30.801 ****[7025:a0b] 0.390000
2013-09-20 11:41:30.801 ****[7025:a0b] 0.080000
2013-09-20 11:41:30.801 ****[7025:a0b] 0.380000
2013-09-20 11:41:30.801 ****[7025:a0b] 42949672.000000
2013-09-20 11:41:30.802 ****[7025:a0b] 0.060000
2013-09-20 11:41:30.802 ****[7025:a0b] 0.080000
2013-09-20 11:41:30.802 ****[7025:a0b] 0.290000
2013-09-20 11:41:30.802 ****[7025:a0b] 42949672.000000
2013-09-20 11:41:30.803 ****[7025:a0b] 0.350000
2013-09-20 11:41:30.803 ****[7025:a0b] 0.180000

i just cant understand why there are results 42949672.000000

Please explain me why this is happening

As i "understand" It must take random(80) - 40 and result / 100.0f so i just don't understand how this (arc4random() % 80) can be more then 79.


Solution

  • The arc4random function is documented to return and u_int32_t. That sounds like an unsigned type, so that when you roll a number < 40 and then subtract 40, you get an arithmetic underflow. That’s where the big number comes from (2^32 – something).