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 ?
Thanks ...
function getRandom(num) {
var my_num = Math.floor(Math.random * num);
return my_num;
};
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 ?
Thanks ...
function getRandom(num) {
var my_num = Math.floor(Math.random * num);
return my_num;
};
Share
Improve this question
asked Oct 14, 2012 at 18:17
nanonerdnanonerd
1,9846 gold badges23 silver badges50 bronze badges
2
- It's zero to one, inclusive of zero but exclusive of one. – Pointy Commented Oct 14, 2012 at 18:21
- Thanks for all the replies below. Pointy hit it as did others below. 1 is not inclusive (this was my misunderstanding, I thought 0 and 1 were both inclusive) so that makes all returns 0 to 51 or a total of 52 return values ... – nanonerd Commented Oct 15, 2012 at 1:29
3 Answers
Reset to default 13Math.floor(Math.random() * num) // note random() is a function.
This will return all integers from 0 (including 0) to num
(NOT including num
).
Math.random
returns 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.
Here's some handy functions from 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)
.
Since you are flooring the result, the maximum number returned is 51
and there are 52
distinct values (counting 0
).
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.