Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Influence Math.random()

I'm looking for a way to influence Math.random().

I have this function to generate a number from min to max:

var rand = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Is there a way to make it more likely to get a low and high number than a number in the middle?

For example; rand(0, 10) would return more of 0,1,9,10 than the rest.

like image 413
Sindre Sorhus Avatar asked Nov 03 '10 19:11

Sindre Sorhus


People also ask

What does Math random () do?

Math.random() The Math.random() function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range.

What is the formula for Math random?

If we wish to generate a random number between two numbers, we can use the formula: RAND() * (b – a) + a, where a is the smallest number and b is the largest number that we wish to generate a random number for.

Is Math random really random?

It may be pointed out that the number returned by Math. random() is a pseudo-random number as no computer can generate a truly random number, that exhibits randomness over all scales and over all sizes of data sets. However, the pseudo-random number generated by Math.

How do you generate a random number in Javascript?

Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.


1 Answers

Is there a way to make it more likely to get a low and high number than a number in the middle?

Yes. You want to change the distribution of the numbers generated.

http://en.wikipedia.org/wiki/Random_number_generation#Generation_from_a_probability_distribution

like image 57
Mark Bolusmjak Avatar answered Sep 22 '22 10:09

Mark Bolusmjak