Javascript:Math.random

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

Javascript: Math.random

javascriptmath

提问by nanonerd

If num parameter is 52, how many possible return values are there? is it 52 or 53? If I understand this correctly, Math.random uses random values from 0 to 1 inclusive. If so, then 0 is a possible return value and so is 52. This results in 53 possible return values. Is this correct? Reason I ask is that a book that I'm learning from uses this code for a deck of cards. I wonder if num should equal 51 ?

如果 num 参数为 52,则有多少个可能的返回值?是52还是53?如果我理解正确,Math.random 使用从 0 到 1 的随机值。如果是,则 0 是可能的返回值,52 也是如此。这将导致 53 个可能的返回值。这个对吗?我问的原因是我正在学习的一本书使用此代码制作一副纸牌。我想知道 num 是否应该等于 51 ?

Thanks ...

谢谢 ...

function getRandom(num) {
    var my_num = Math.floor(Math.random * num);
    return my_num;
};

回答by jbabey

Math.floor(Math.random() * num) // note random() is a function.

This will return all integers from 0 (including 0) to num(NOT including num).

这将返回从 0(包括 0)到num(不包括num)的所有整数。

Math.randomreturns a number between 0 (inclusive) and 1 (exclusive). Multiplying the result by X gives you between 0 (inclusive) and X (exclusive). Adding or subtracting X shifts the range by +-X.

Math.random返回 0(包含)和 1(不包含)之间的数字。将结果乘以 X 得到 0(包含)和 X(不包含)之间的值。添加或减去 X 会将范围移动 +-X。

Here's some handy functions from MDN:

以下是MDN的一些方便的功能:

// Returns a random number between 0 (inclusive) and 1 (exclusive)
function getRandom() {
  return Math.random();
}

// Returns a random number between min and max
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

回答by Felix Kling

Since Math.randomreturns a real number between [0,1)(1is notinclusive), multiplying the result returns a real number between [0, 52).

由于Math.random回报率之间的实数[0,1)1包括在内),将结果乘以返回之间的实数[0, 52)

Since you are flooring the result, the maximum number returned is 51and there are 52distinct values (counting 0).

由于您正在计算结果,返回的最大数量是51并且存在52不同的值(计数0)。

回答by Anoop

Since value of Math.random varies from 0 to 1(exclusive); so if you pass 52 in getRandom, return value will vary from 0 to 52(exclusive). so getRandom can return only 52 values. as you are using Math.floor. the max value can be returned is 51.

由于 Math.random 的值在 0 到 1(不包括)之间变化;因此,如果您在 getRandom 中传递 52,返回值将在 0 到 52(不包括)之间变化。所以 getRandom 只能返回 52 个值。当您使用 Math.floor 时。可以返回的最大值是 51。