JavaScript随机正数或负数

问题描述 投票:39回答:6

我需要创建一个随机-1或1来乘以已存在的数字。问题是我当前的随机函数生成-1,0或1.这样做的最有效方法是什么?

javascript random
6个回答
117
投票

不要使用现有的功能 - 只需调用Math.random()。如果<0.5则为-1,否则为1:

var plusOrMinus = Math.random() < 0.5 ? -1 : 1;

48
投票

我一直都是粉丝

Math.round(Math.random()) * 2 - 1

因为它只是有道理。

  • Math.round(Math.random())会给你0或1
  • 将结果乘以2将得到0或2
  • 然后减去1会得到-1或1。

直观!


11
投票

就是图个好玩儿:

var plusOrMinus = [-1,1][Math.random()*2|0];  

要么

var plusOrMinus = Math.random()*2|0 || -1;

但要使用您认为可维护的内容。


11
投票

为什么不尝试:

(Math.random() - 0.5) * 2

50%的可能性具有负值,并且还具有生成随机数的额外好处。

或者如果确实需要-1/1:

Math.ceil((Math.random() - 0.5) * 2) < 1 ? -1 : 1;

4
投票

正如先前的答案所示,有很多方法可以做到这一点。

Math.round()和Math.random的最快组合:

// random_sign = -1 + 2 x (0 or 1); 
random_sign = -1 + Math.round(Math.random()) * 2;   

您还可以使用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() ) );

0
投票

我正在使用underscore.js shuffle

var plusOrMinus = _.shuffle([-1, 1])[0];
© www.soinside.com 2019 - 2024. All rights reserved.