Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Math.random

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;
};
like image 884
nanonerd Avatar asked Oct 14 '12 18:10

nanonerd


3 Answers

Math.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;
}
like image 186
jbabey Avatar answered Oct 28 '22 03:10

jbabey


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).

like image 43
Felix Kling Avatar answered Oct 28 '22 05:10

Felix Kling


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.

like image 36
Anoop Avatar answered Oct 28 '22 04:10

Anoop