JavaScript 随机正数或负数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8611830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:43:42  来源:igfitidea点击:

JavaScript Random Positive or Negative Number

javascriptrandom

提问by Ash Blue

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?

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

回答by ziesemer

Don't use your existing function - just call Math.random(). If < 0.5 then -1, else 1:

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

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

回答by majman

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.

  • Math.round(Math.random())会给你 0 或 1

  • 将结果乘以 2 将得到 0 或 2

  • 然后减去 1 得到 -1 或 1。

Intuitive!

直觉的!

回答by newshorts

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.

50% 的机会有一个负值,但仍然有一个随机数生成的额外好处。

Or if really need a -1/1:

或者如果真的需要 -1/1:

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

回答by RobG

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.

但是使用你认为可以维护的东西。

回答by Nabil Kadimi

There are really lots of ways to do it as previous answers show.

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

The fastest being combination of Math.round() and Math.random:

最快的是 Math.round() 和 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):

您还可以使用 Math.cos() (这也很快):

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

回答by Adam Schultz

I'm using underscore.js shuffle

我正在使用underscore.js shuffle

var plusOrMinus = _.shuffle([-1, 1])[0];