Search code examples
objective-cios8xcode6negative-numberarc4random

arc4random() positive & negative numbers


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.


Solution

  • 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;