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?
8 Answers
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;
-
6
I've always been a fan of
Math.round(Math.random()) * 2 - 1
as it just sort of makes sense.
Math.round(Math.random())
will give you 0 or 1Multiplying the result by 2 will give you 0 or 2
And then subtracting 1 gives you -1 or 1.
Intuitive!
-
1In my opinion this is a better "random" - or + creator. The selected answer just doesn't work for me because what if i want a number that is less than 4 that isn't negative? This is just an all around better solution.– BrendanAug 20, 2014 at 22:30
-
@Brendan - While that I agree that this is a more flexible solution, the OP's requirement was specifically for needing to return a "random -1 or +1". For what it's worth, this solution, while more flexible - also requires more operations - in terms of an extra call to
Math.round
, multiplication, and subtraction - vs. a single conditional check.– ziesemerJan 2, 2019 at 14:55
why dont you try:
(Math.random() - 0.5) * 2
50% chance of having a negative value with the added benefit of still having a random number generated.
Or if really need a -1/1:
Math.ceil((Math.random() - 0.5) * 2) < 1 ? -1 : 1;
-
1
-
I think this does not give a perfectly equal +/- random number, or am I wrong ?
0.999... - 0.5 = 0.4999...
, but0 - 0.5 = -0.5
. (as Math.random() returns 0 to 0.999...)– kcaDec 4, 2019 at 13:41
Just for the fun of it:
var plusOrMinus = [-1,1][Math.random()*2|0];
or
var plusOrMinus = Math.random()*2|0 || -1;
But use what you think will be maintainable.
-
1On one hand, I should say there's something to be said for readability. On the other hand, kudos for shaving 3 characters off of my answer (though I could argue that all 3 characters are unnecessary whitespace). Mine is 1 character shorter if you also eliminate the
0
from0.5
. :-)– ziesemerDec 23, 2011 at 4:07
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() ) );
Math.random() - Math.random()
Or
Math.random() * (Math.random() > 0.5 ? 1 : -1 )
Here you go