Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly generate "-1" or "1" - Shortest Method

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

like image 562
Albert Renshaw Avatar asked Feb 25 '13 21:02

Albert Renshaw


1 Answers

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

or arc4random_uniform(2)*2 - 1

like image 93
Sebastian Avatar answered Sep 28 '22 07:09

Sebastian