Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
};
like image 349
vasili111 Avatar asked Dec 20 '25 11:12

vasili111


1 Answers

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.

like image 122
Greg Hewgill Avatar answered Dec 23 '25 06:12

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!