JavaScript Random Positive or Negative Number

2019-03-08 01:44发布

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?

6条回答
再贱就再见
2楼-- · 2019-03-08 02:13

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;
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-03-08 02:13

I'm using underscore.js shuffle

var plusOrMinus = _.shuffle([-1, 1])[0];
查看更多
We Are One
4楼-- · 2019-03-08 02:22

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 1

  • Multiplying the result by 2 will give you 0 or 2

  • And then subtracting 1 gives you -1 or 1.

Intuitive!

查看更多
来,给爷笑一个
5楼-- · 2019-03-08 02:32

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;
查看更多
家丑人穷心不美
6楼-- · 2019-03-08 02:33

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() ) );
查看更多
一夜七次
7楼-- · 2019-03-08 02:37

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.

查看更多
登录 后发表回答