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?
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With