# ExpRand

By John
on October 14, 2005

Version: 1

Type: Function

Category: Math Functions

Description: Exponentially weighted random number generator. Generates random number useing the formula f(x)=x^a where x is a random number and a is the weight.

Function imputs are \$min, \$max, and \$average.
Function returns random float between \$min and \$max. If run multiple times the average should be near \$average.

File contain test code (all code outside the function) which can be removed.

Math behind the code:
f(x)=x^a where x is a random number between 0 and \$maxrand

From hear on \$min is assumed to be 0, x is assumed to be \$maxrand, and avg is \$average
Average value is equil to area under the curve devided by x
A(x)=(x^(a+1)/(a+1) where A(x) is area
avg=(x^(a+1))/(a+1)x
simplify
avg=(x^a)/(a+1)

F(x)=x^a becomes
y=x^a where y is \$max
x = y^(1/a)
avg=(x^a)/(a+1)
avg=((y^(1/a))^a)/(a+1) substitution
avg=y/(a+1) simplify
a=(y/avg)-1 solve for a
since y(\$max) is given and avg(\$average) is give you now have a
\$exp = (\$max/\$average)-1;

x = y^(1/a)
since y(\$max) is given and a is now knowen you now have x(\$maxrand)
\$maxrand = pow(\$max,(1/\$exp));

f(x)=x^a where x is a random number between 0 and \$maxrand can now be calculated
\$rand = mt_rand(0,\$maxrand);
\$resault = pow(\$rand,\$exp);

L0ok at the code to see how \$min was added

```<?php

\$min_val = 3;
\$max_val = 20;
\$average_val = 5;

\$loops = 0;

while (\$loops < 100) {

\$total += exprand(\$min_val, \$max_val, \$average_val);

\$loops ++;
}

\$average = \$total/\$loops;
echo '<br>';
echo gettype(\$total);
echo "<br> \$total <br> \$loops <br>";
echo \$average;

//exponentially weighted random number generator
//generates random numbers throught the base formula
//f(x)=x^a where x is a random number and a is the weight
//function imputs are \$min, \$max, and \$average
//function returns random float between \$min and \$max
//if run multiple times the average should be near \$average
function exprand(\$min, \$max, \$average) {
//the origional exprand didn't accept \$min
//the next 2 lines and the second \$resault line add \$min functionality
\$max -=\$min;
\$average -=\$min;

//calculating exponent
\$exp = (\$max/\$average)-1;
//calculating max value for mt_rand
\$maxrand = pow(\$max,(1/\$exp));

//mt_rand returns integers
//rounding errors were causing major problems
//next 3 lines of code generate a random number with accuracy to the millionth
\$maxrand *= 1000000;
\$rand = mt_rand(0,\$maxrand);
\$rand /= 1000000;

//applying curve to \$rand
\$resault = pow(\$rand,\$exp);

//add \$min back in
\$resault += \$min;

return \$resault;
}
?>```
﻿