Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random numbers with less probabilities of bigger numbers

I want to implement a random number generator which lets me set the maximum number I want but also lets me tweak the probabilities to make it harder to get bigger number.

Using this would allocate the same probabilities to any value in the range of 100.

Math.floor(Math.random()*100);

How can I make numbers get progressively harder to appear as the number gets closer to the limit (100)?

like image 877
lisovaccaro Avatar asked Jan 14 '23 20:01

lisovaccaro


2 Answers

Square the result of Math.random:

var result = Math.random();
result = result * result;
result *= 100;
result = Math.floor(result);

You can adjust the curve by adjusting the exponent. Here's a few graphs of different exponents:

The larger exponents are steeper.

If you're going to use a non-integer exponent, you'll need to use Math.pow.

like image 50
icktoofay Avatar answered Jan 31 '23 00:01

icktoofay


Simply use a mathematically function that has curve giving you the required probability weighting. For example, you could 'square' your number:

enter image description here

var num = Math.pow(Math.floor(Math.random()*10), 2);

The above generates a random number between 1-10 then squares it to give a random number between 1-100, but weighted towards lower numbers.

You can further increase the weighting by using higher power.

like image 40
ColinE Avatar answered Jan 30 '23 23:01

ColinE