Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Get a random number within range min and max. Both exclusive

I wonder what is the best way to generate a random floating number between min and max. Both min and max are EXCLUSIVE.

For example, min = -1, max = 100. Then the random number can be -0.999 or 99.999, but cannot be -1 or 100.

The way I come up is first generate a random number between -1 (inclusive) and 100 (exclusive):

Math.random()*(max-min)+min

And if the value is equal to -1, get another random number until it's not -1.

The whole thing would be:

var min = -1, max = 100;
var rand = min;
while(rand==min)
    rand = Math.random()*(max-min)+min;

Is there an even better way to do this so I don't have to possibly run Math.random() several times?

like image 523
Shawn Avatar asked Oct 17 '25 03:10

Shawn


2 Answers

You could check the random number first and use only values not equal of zero.

var min = -1,
    max = 100,
    r;

while (!(r = Math.random()));        // generate and check and use only r !== 0 values
console.log(r * (max - min) + min);
like image 140
Nina Scholz Avatar answered Oct 18 '25 21:10

Nina Scholz


Just use your code removing the limits with the desired precission

var p = 0.000001; //desired precission
var min = -1+p, max = 100-p;
rand = Math.floor(Math.random()*(max-min)+min)
like image 21
pedrofb Avatar answered Oct 18 '25 19:10

pedrofb



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!