Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - Random results is either 1 or -1

I am trying randomly generate a positive or negative number and rather then worry about the bigger range I am hoping to randomly generate either 1 or -1 to just multiply by my other random number.

I know this can be done with a longer rule of generating 0 or 1 and then checking return and using that to either multiply by 1 or -1.

Hoping someone knows of an easier way to just randomly set the sign on a number. Trying to keep my code as clean as possible.

like image 321
Armychimp Avatar asked Aug 31 '09 21:08

Armychimp


2 Answers

I like to use arc4random() because it doesn't require you to seed the random number generator. It also conveniently returns a uint_32_t, so you don't have to worry about the result being between 0 and 1, etc. It'll just give you a random integer.

int myRandom() {
  return (arc4random() % 2 ? 1 : -1);
}
like image 88
Dave DeLong Avatar answered Oct 20 '22 02:10

Dave DeLong


If I understand the question correctly, you want a pseudorandom sequence of 1 and -1:

int f(void)
{
        return random() & 1 ? 1 : -1;
    //  or...
    //  return 2 * (random() & 1) - 1;
    //  or...
    //  return ((random() & 1) << 1) - 1;
    //  or...
    //  return (random() & 2) - 1; // This one from Chris Lutz
}

Update: Ok, something has been bothering me since I wrote this. One of the frequent weaknesses of common RNGs is that the low order bits can go through short cycles. It's probably best to test a higher-order bit:   random() & 0x80000 ? 1 : -1

like image 35
DigitalRoss Avatar answered Oct 20 '22 01:10

DigitalRoss