lisovaccaro
lisovaccaro

Reputation: 33956

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

Upvotes: 4

Views: 2190

Answers (3)

icktoofay
icktoofay

Reputation: 129001

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.

Upvotes: 6

Nicholas E.
Nicholas E.

Reputation: 109

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

Or something similar.

Upvotes: -1

ColinE
ColinE

Reputation: 70142

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.

Upvotes: 4

Related Questions