arc4random() positive & negative numbers

2.4k views Asked by At

Can someone tell me how to properly write

arc4random() %#;

to include not only positive numbers but negative numbers as well? I'm trying to have an image (SKSpriteNode from Sprite Kit) be able to randomly move in any direction within a 2D environment.

2

There are 2 answers

0
AMI289 On BEST ANSWER

arc4random() return type is an u_int32_t which is an unsigned int so it can't directly return a negative number.
You will need to 'manipulate' it in order to receive a positive or negative range.

First, I would like to suggest to use arc4random_uniform() instead of arc4random() % since it avoids "modulo bias" when the upper bound is not a power of two.

As for your question, you can do the following by subtracting the wanted range.
For Example:

arc4random_uniform(100);  

Will give values between 0 and 99,
But by subtracting 50 like this:

arc4random_uniform(100) - 50;  

We will now get a random value between -50 and 49;

EDIT- If you assign the results to a variable, I think you will need to type cast the arc4random_uniform result to avoid compiler warning, although I am not sure if necessary.
So it would look like this:

int randomNumber = (int)arc4random_uniform(100) - 50;
3
Caleb On

to include not only positive numbers but negative numbers as well?

You can't. arc4random() returns an unsigned value (u_int32_t).

What you can do, though, is shift the range of returned values by subtracting half the range. That is, if you'd normally do something like:

 int x = arc4random() % 20;

to get a value in the range [0, 20), you could instead say:

 int x = (arc4random() % 20) - 10;

to get a value in the range [-10, 10).