I need to create a random -1 or 1 to multiply an already existing number by. Issue is my current random function generates a -1, 0, or 1. What is the most efficient way of doing
There are really lots of ways to do it as previous answers show.
The fastest being combination of Math.round() and Math.random:
// random_sign = -1 + 2 x (0 or 1);
random_sign = -1 + Math.round(Math.random()) * 2;
You can also use Math.cos() (which is also fast):
// cos(0) = 1
// cos(PI) = -1
// random_sign = cos( PI x ( 0 or 1 ) );
random_sign = Math.cos( Math.PI * Math.round( Math.random() ) );