Generate random numbers with less probabilities of

2019-04-09 22:18发布

问题:

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)?

回答1:

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:

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



回答2:

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

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.



回答3:

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

Or something similar.