简体   繁体   English

Javascript:Math.random

[英]Javascript: Math.random

If num parameter is 52, how many possible return values are there? 如果num参数是52,那么有多少可能的返回值? is it 52 or 53? 是52还是53? If I understand this correctly, Math.random uses random values from 0 to 1 inclusive. 如果我理解正确,Math.random使用从0到1的随机值。 If so, then 0 is a possible return value and so is 52. This results in 53 possible return values. 如果是,那么0是可能的返回值,因此是52.这导致53个可能的返回值。 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是否应该等于51?

Thanks ... 谢谢 ...

function getRandom(num) {
    var my_num = Math.floor(Math.random * num);
    return my_num;
};
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.random returns a number between 0 (inclusive) and 1 (exclusive). Math.random返回0(包括)和1(不包括)之间的数字。 Multiplying the result by X gives you between 0 (inclusive) and X (exclusive). 将结果乘以X可以得到0(包括)和X(不包括)。 Adding or subtracting X shifts the range by +-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;
}

Since Math.random returns a real number between [0,1) ( 1 is not inclusive), 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 51 and there are 52 distinct values (counting 0 ). 由于您对结果进行了布局,因此返回的最大数量为51并且有52不同的值(计数为0 )。

Since value of Math.random varies from 0 to 1(exclusive); 由于Math.random的值从0变为1(不包括); so if you pass 52 in getRandom, return value will vary from 0 to 52(exclusive). 因此,如果您在getRandom中传递52,则返回值将在0到52之间变化(不包括)。 so getRandom can return only 52 values. 所以getRandom只能返回52个值。 as you are using Math.floor. 因为你正在使用Math.floor。 the max value can be returned is 51. 最大值可以返回51。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM