Php – Adjust algorithm for generating random strength values

algorithmPHPrandomstatistics

A few days ago, you helped me to find out an algorithm for generating random strength values in an online game (thx especially John Rasch).

function getRandomStrength($quality) {
    $rand = mt_rand()/mt_getrandmax();
    $value = round(pow(M_E, ($rand - 1.033) / -0.45), 1);
    return $value;
}

This function generates values between 1.1 and 9.9. Now I want to adjust this function so that it gives me values of the same probability but in another interval, e.g. 1.5 to 8.0. It would be perfect if you could achieve this with additional parameters.

It would be great if you could help me. Thanks in advance!

Best Answer

The values 1.033 and -0.45 in the original code are the magic numbers that provide the scale 1.1 - 9.9. You should get the same results if you pass in 1.1 and 9.9 as the parameters $low and $high in the following code.

function getRandomStrength($low, $high) {
    // TODO: validate the input
    $ln_low = log( $low, M_E );
    $ln_high = log( $high, M_E );
    $scale = $ln_high - $ln_low;

    $rand = ( mt_rand() / mt_getrandmax() ) * $scale + $ln_low;
    $value = round( pow( M_E, $rand), 1 );
    return $value;
}

You should be able to pass in any range for $low and $high and get a logarithmic distribution in that range. (I'll leave range validity checking to you, but 0 < $low < $high should be true.)

This works by back calculating the linear scale necessary to generate the logarithmic scale in the provided range. If I want my log scale to be 1.1 - 9.9, for example, I take the natural log of each of those values, giving me 0.0953 - 2.2925. I then generate a random number in this linear range, and raise e to the random power to convert it back to the log range.