5

I need to randomly generate either a "-1" or a "1" to determine the sign of a number randomly... What's the shortest method? I am currently using this but it seems pretty long:

sign = (round((arc4random() % 2)))-((round((arc4random() % 2))) == 0);

Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195

2 Answers2

12

What about arc4random_uniform(2) ? -1 : 1?

or arc4random_uniform(2)*2 - 1

Sebastian
  • 7,670
  • 5
  • 38
  • 50
  • Nice, its like a random binary op – Shizam Feb 25 '13 at 21:29
  • Oh, very nice! Multiplying by 2 and subtracting 1, didn't even think of that! :) – Albert Renshaw Feb 25 '13 at 21:29
  • 2
    **arc4random_uniform() will return a uniformly distributed random number less than upper_bound.** It avoids modulo bias. See the [arc4random manpage](http://www.manpagez.com/man/3/arc4random/) – Sebastian Feb 25 '13 at 21:32
  • 1
    Another possibility (not really worth another answer): `static const int tmp[] = {-1, 1}; return tmp[arc4random_uniform(2)];` – twalberg Feb 25 '13 at 21:46
  • @twalberg That's cool too! An array would be very helpful if it was more than just 2 numbers (i.e. -1 an d 1) – Albert Renshaw Feb 25 '13 at 22:16
1
short int randomNumber () {
return arc4random() % 2 ? 1 : -1;
}
Lluís
  • 578
  • 1
  • 5
  • 10