Home >Backend Development >PHP Tutorial >How Can I Generate Random Numbers in PHP with Weighted Probabilities?

How Can I Generate Random Numbers in PHP with Weighted Probabilities?

Susan Sarandon
Susan SarandonOriginal
2024-12-08 21:32:11784browse

How Can I Generate Random Numbers in PHP with Weighted Probabilities?

Generating Random Results with Weighted Probabilities in PHP

The generation of random numbers in PHP is well-documented. However, achieving randomization with predefined probabilities requires an additional approach. This question focuses on generating random values between 1-10 with a higher probability of obtaining 3, 4, and 5 than 8, 9, and 10.

Drawing inspiration from @Allain's suggestion, a custom function was developed to facilitate this weighted randomization in PHP:

/**
 * getRandomWeightedElement()
 * Utility function for getting random values with weighting.
 * Pass in an associative array, such as array('A'=>5, 'B'=>45, 'C'=>50)
 * An array like this means that "A" has a 5% chance of being selected, "B" 45%, and "C" 50%.
 * The return value is the array key, A, B, or C in this case.  Note that the values assigned
 * do not have to be percentages.  The values are simply relative to each other.  If one value
 * weight was 2, and the other weight of 1, the value with the weight of 2 has about a 66%
 * chance of being selected.  Also note that weights should be integers.
 * 
 * @param array $weightedValues
 */
function getRandomWeightedElement(array $weightedValues) {
    $rand = mt_rand(1, (int) array_sum($weightedValues));

    foreach ($weightedValues as $key => $value) {
        $rand -= $value;
        if ($rand <= 0) {
            return $key;
        }
    }
}

In this function, the input is an associative array where the keys represent the desired outcomes, and the values are their corresponding probabilities. These probabilities do not have to be percentages but rather relative to each other.

By utilizing a combination of PHP's random number generator (mt_rand()) and a cumulative probability approach, the function picks a random value from the array based on the assigned probabilities. This allows for the generation of random results with user-defined biases, making it a versatile and effective tool for various applications.

The above is the detailed content of How Can I Generate Random Numbers in PHP with Weighted Probabilities?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn