2

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(); } }; 

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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) 

9 Comments

No, that will generate a random number between X and X+Y.
@Guffa no, it wont. Note the (Y - 1)
@Guffa the OP's formula would have returned that. Hence the question being posted on SO
You are missing the point completely. The code doesn't return a random number between X and Y, it returns a random number between X and X+Y.
@Guffa Sure? Let x = 1, y = 10, and Math.random() = 1 (for a maximum). I'll let you do the math.
|
0

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

just use round

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.