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 this?
Don't use your existing function - just call Math.random()
. If < 0.5 then -1, else 1:
var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
The Math.random()
method returns a floating-point number that's greater than or equal to 0 and less than 1.