vasili111
vasili111

Reputation: 6940

Some thoughts about generating random number

I wanted some information about generating random integers. I look for it in Google and Stack Overflow and mostly found code like this (in case we want numbers from 1 to 52):

var randInt=function(){
   number=Math.floor(Math.random()*52+1);
};

and

var randNumMin = 1;
var randNumMax = 52;
var randInt = function (){
   number = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);
};

I read some references about Math.random and found that it is generating numbers from 0 to 1. In case Math.random generates 1, we will get number 5, so it means we will get error. I agree that it is very rare case, but it is possible. I slightly modified code to avoid that error (in our case generation of number 53). Here I think is a right code for generation random numbers in JavaScript. In your examples it generates only integers but I think it is possible to modify code and generate any kind of number:

var randInt = function(){
    number = Math.floor(Math.random()*52+1);
    if (number === 53){
       randInt();
    }
};

and

var randNumMin = 1;
var randNumMax = 52;
var randInt = function (){
    number = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);
    if (number===53){
        randInt();
    }
};

Upvotes: 2

Views: 216

Answers (3)

Phillip Schmidt
Phillip Schmidt

Reputation: 8818

Just take your first code sample, and subtract one from the 52. The general formula is this:

random number between X and Y = (Y - X) * Math.random() + X

or for integers,

Math.round((Y - X) * Math.random() + X)

or to be more accurate (as pointed out by @Guffa),

Math.floor((Y-(X-1)) * Math.random() + X)

Upvotes: 2

Anonymous
Anonymous

Reputation: 4630

You dont need to use floor because it will cut down the result indeed.

just use round

Math.round(Math.random(51))+1

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 994927

The Math.random() function generates random numbers x where 0 <= x < 1. So it will never generate exactly 1, although it might come really close.

From the documentation for random:

Returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

Upvotes: 11

Related Questions