我需要创建一个随机-1或1来乘以已存在的数字。问题是我当前的随机函数生成-1,0或1.这样做的最有效方法是什么?
不要使用现有的功能 - 只需调用Math.random()
。如果<0.5则为-1,否则为1:
var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
我一直都是粉丝
Math.round(Math.random()) * 2 - 1
因为它只是有道理。
Math.round(Math.random())
会给你0或1直观!
就是图个好玩儿:
var plusOrMinus = [-1,1][Math.random()*2|0];
要么
var plusOrMinus = Math.random()*2|0 || -1;
但要使用您认为可维护的内容。
为什么不尝试:
(Math.random() - 0.5) * 2
50%的可能性具有负值,并且还具有生成随机数的额外好处。
或者如果确实需要-1/1:
Math.ceil((Math.random() - 0.5) * 2) < 1 ? -1 : 1;
正如先前的答案所示,有很多方法可以做到这一点。
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() ) );
var plusOrMinus = _.shuffle([-1, 1])[0];