Javascript 负值和正值之间的随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13455042/
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 12:08:39  来源:igfitidea点击:

Random number between negative and positive value

javascriptrandomnumbers

提问by user1835929

Possible Duplicate:
Generating random numbers in Javascript in a specific range?

可能的重复:
在特定范围内的 Javascript 中生成随机数?

How can i get a random value between, for example, from -99 to 99, excluding 0?

我怎样才能得到一个随机值,例如,从 -99 到 99,不包括 0?

回答by LittleSweetSeas

var num = Math.floor(Math.random()*99) + 1; // this will get a number between 1 and 99;
num *= Math.floor(Math.random()*2) == 1 ? 1 : -1; // this will add minus sign in 50% of cases

回答by Bruno Vieira

This returns what you want

这将返回你想要的

function getNonZeroRandomNumber(){
    var random = Math.floor(Math.random()*199) - 99;
    if(random==0) return getNonZeroRandomNumber();
    return random;
}

Here's a functional fiddle

这是一个功能性的小提琴

EDIT

编辑

To contribute for future readers with a little debate happened in the comments which the user @MarkDickinson made a indeed relevant contribution to my first code posted, I've decided to make another fiddle with a fast comparison between using Math.floor()and Math.round()functions to return the value the op wanted.

为了为未来的读者做出贡献,在评论中发生了一些争论,用户@MarkDickinson 对我发布的第一个代码做出了确实相关的贡献,我决定再做一个快速比较 usingMath.floor()Math.round()函数之间的快速比较以返回值欧普想要。

First Scenario: Using var random = Math.round(Math.random()*198) - 99;(My first suggestion)

第一个场景:使用var random = Math.round(Math.random()*198) - 99;(我的第一个建议)

function getNonZeroRandomNumberWithMathRound(){
    var random = Math.round(Math.random()*198) - 99;
    if(random==0) return getNonZeroRandomNumber();
    return random;
}

Second scenario: Using var random=Math.floor(Math.random()*199) - 99;(Mark suggestion)

第二种情况:使用var random=Math.floor(Math.random()*199) - 99;(标记建议)

function getNonZeroRandomNumberWithMathFloor(){
    var random = Math.floor(Math.random()*199) - 99;
    if(random==0) return getNonZeroRandomNumber();
    return random;
}

Methodology

方法

Since it's a short debate I've chosen fiddle.netto do the comparison.

由于这是一场简短的辩论,我选择了fiddle.net来进行比较。

The test consists of running the above functions 100.000 times and then retrieving how much times the extreme numbers 99and -99would appear against a other number, let's say 33and -33.

测试包括运行上述函数 100.000 次,然后检索极端数字出现的次数99以及-99与其他数字相对应的次数,例如33-33

The test will then give a simple output consisting of the percentage of appearances from 99and -99and the percentage of appearances of 33and -33.

然后,测试将给出一个简单的输出由来自露面的百分比99-99和的出场率33-33

It'll be used the Webkit implementation from Safari 6.0.2to the give the output from this answer but anyone can test with your favourite browser late on fiddle.net

它将使用 Webkit 实现Safari 6.0.2来给出此答案的输出,但任何人都可以在fiddle.net上使用您最喜欢的浏览器进行测试

Result from first scenario:

第一个场景的结果:

  • Percentage of normal ocurrences:0.97%
  • Percentage of extreme ocurrences:0.52%
  • Percentage of extreme ocurrences relative to normal ocurrences:53.4% // Half the chances indeed
  • 正常发生率:0.97%
  • 极端事件的百分比:0.52%
  • 极端事件相对于正常事件的百分比:53.4% // 确实是一半的机会

Result from second scenario:

第二种情况的结果:

  • Percentage of normal ocurrences:1.052%
  • Percentage of extreme ocurrences:0.974%
  • Percentage of extreme ocurrences relative to normal ocurrences:92% //Closer of a fair result with a minimal standard deviation
  • 正常发生率:1.052%
  • 极端事件的百分比:0.974%
  • 极端事件相对于正常事件的百分比:92% //以最小标准偏差接近公平结果

The result can be seen here: http://jsfiddle.net/brunovieira/LrXqh/

结果可以在这里看到:http: //jsfiddle.net/brunovieira/LrXqh/

回答by I Hate Lazy

Here's a generalized solution that will let you set the boundaries, and opt in/out of including the 0.

这是一个通用的解决方案,可让您设置边界,并选择加入/退出包含0.

var pos = 99,
    neg = 99,
    includeZero = false,
    result;

do result = Math.ceil(Math.random() * (pos + neg)) - neg;
while (includeZero === false && result === 0);

The posand negvalues are inclusive.

posneg值包含在内。

This way there's no requirement that the positive and negative ranges be balanced.

这样就不需要平衡正负范围。



Or if you're worried about the rerun due to a single excluded value, you can just make the initial range less by one, and add 1to any result greater than or equal to 0.

或者,如果您担心由于单个排除值而重新运行,您可以将初始范围减一,并添加1到任何大于或等于 的结果0

var pos = 5,
    neg = 5,
    result;

result = Math.floor(Math.random() * (pos + neg)) - neg;
result = result < 0 ? result : result + 1;


That last line could be shorter if you prefer:

如果您愿意,最后一行可以更短:

result += (result >= 0)