Random number with probability

2019-07-27 21:44发布

问题:

I am trying to generate a random number and have a probability of x% to get closer of the max value.

Problem is that I have no idea how to do this, unless I make some steps?

Let's say I'll generate a random number between 1 and 3000.

$number = mt_rand(1, 3000)

This will return 2700 for example. I would like it to be closer to 1 than 3000.

How should I implement a function that will only have a 10% chance to get near 3000?

回答1:

Based on the comments on the question you can use the mt_rand function twice. First - to check if it should be the 90% (where the value is random of 1-100), and if not - it is the other 10%, where the value is random of 1-3000:

$number = mt_rand(0, 9) == 0 ? mt_rand(1, 3000) : mt_rand(1, 100);