mardi 15 novembre 2016

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

This question already has an answer here:

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 easier way to do this?




Aucun commentaire:

Enregistrer un commentaire