G
G
g1tufix2021-07-15 22:59:35
PHP
g1tufix, 2021-07-15 22:59:35

How to generate a random number, the larger the number, the less chance?

It is necessary to generate a random number in a certain range, while the chance for a larger number should be less (The larger the number, the less the chance of it falling out)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
vilinyh, 2021-07-15
@vilinyh

Uh, a problem from school mathematics, I would like to remember more.
If I think correctly, we need to take the probability density function, integrate over a given interval, take the inverse function from the integral and substitute the arguments with a uniform distribution generator for this function.
Well, that is, if you have a linear decrease in the probability f (x) = -x, it will be a rotated square root on a given interval (something like, count who has not forgotten the integrals from school yet).
In general it turns out:

/**
 * Generates a random number between 0.00 and 1.00
 */
function generateNum()
{
    return 1 - sqrt(rand(0, 1000)/1000);
}

Test:
$nums = [];
for($i = 0; $i < 10000; ++$i) {
    $index = sprintf('%.1f', floor(generateNum() * 10) / 10);
    $nums[$index] = ($nums[$index] ?? 0) + 1;
}

ksort($nums);

var_dump($nums);

The resulting probability density (frequency):
60f0a01d70601334855555.png

S
Stalker_RED, 2021-07-16
@Stalker_RED

If you multiply two random numbers, then you will no longer get a linear distribution, but a Pearson distribution.

You can play around with the numbers by adding some coefficients.

C
catanfa, 2021-07-22
@catanfa

just loop from 1 to your max, generate either 0 or 1 randomly. If the roll is 1, then continue the loop. If 0 is dropped, then stop the loop. The result will be the current iteration of the loop. Thus, the probability of each larger number decreases.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question