lundi 17 septembre 2018

How to get a random number between x and y e.g. (-1000 and 77) in Javascript?

I know that similar questions have been asked multiple times but I cannot find one where the odds of being negative or positive are greatly outweighed on one side more than the other. Probably because it's buried beneath all of the other duplicates but again I couldn't find one after searching.

Randomly flipping between negative and positive 50% of the time would not give a truly random number as you will have just as many positives as negatives even though theoretically you'd be more likely to get negative numbers.

The common approach I've seen only works when given positive numbers:

return Math.floor(Math.random() * (max - min + 1)) + min;

This approach works but they are evenly distributed in negative vs positive as the question was to Create a random number between -100 and 100 in JavaScript?

var randomNumber = Math.floor(Math.random() * 201) - 100;

It doesn't seem like it should be this complicated but I'm struggling to wrap my head around a logical way to do this. I know I could be drastic and start shoving all of the values that would theoretically exist into an array, then randomly pulling a random positive index out from the array, but that sounds horribly inefficient.

I could take the probability of being positive vs negative first, then based on a random percentage determine if I want it to be positive or negative from that, and then get a random value within my range using the first aforementioned option multiplying by -1 at the end if it's supposed to be negative but that sounds like overkill too for such a simple sounding task.




Aucun commentaire:

Enregistrer un commentaire