Question

In a cocos2d game, I use arc4random to generate random numbers like this:

    float x = (arc4random()%10 - 5)*delta;

(delta is the time between updates in the scheduled update method)

    NSLog(@"x: %f", x);

I have been checking them like that.

Most of the numbers that I get are like this:

    2012-12-29 15:37:18.206 Jumpy[1924:907] x: 0.033444

or

    2012-12-29 15:37:18.247 Jumpy[1924:907] x: 0.033369

But for some reason I get numbers like this sometimes:

    2012-12-29 15:37:18.244 Jumpy[1924:907] x: 71658664.000000

Edit: Delta is almost always:

    2012-12-29 17:01:26.612 Jumpy[2059:907] delta: 0.016590

I thought it should return numbers in a range of -5 to 5 (multiplied by some small number). Why I am getting numbers like this?

Was it helpful?

Solution

arc4random returns a u_int32_t. The u_ part tells you that it's unsigned. So all of the operators inside the parentheses use unsigned arithmetic.

If you perform the subtraction 2 - 5 using unsigned 32-bit arithmetic, you get 232 + 2 - 5 = 232 - 3 = 4294967293 (a “huge number”).

Cast to a signed type before performing the subtraction. Also, prefer arc4random_uniform if your deployment target is iOS 4.3 or later:

float x = ((int)arc4random_uniform(10) - 5) * delta;

If you want the range to include -5 and 5, you need to use 11 instead of 10, because the range [-5,5] (inclusive) contains 11 elements:

float x = ((int)arc4random_uniform(11) - 5) * delta;

OTHER TIPS

arc4random returns a u_int32_t, an unsigned type. The modulus is also performed using unsigned arithmetic, which yields a number between 0 and 9, as expected (by the way, don't ever do this; use arc4random_uniform instead). You then subtract 5, which is interpreted as an unsigned value, yielding a possibly huge positive value due to underflow.

The solution is to explicitly type the 5 by storing it in a variable of signed type or with a suffix (like 5L).

Looks like arc4random % 10 becomes less than 5, and you are working with negative integer later.

What is the value of delta?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top