Floydian Posted June 11, 2009 Posted June 11, 2009 The code snippet below will generate a random number within a certain distance from zero. $variance is a percentage, with 100% being equal to a distance of -1 to 1, and 50% being equal to a distance of -0.5 to 0.5. /** * Generates a random number within a given range. * * @param float $variance * A range above and below zero. * @return float * A number greater than or less than zero within a range defined by $varience. */ function deviation($variance) { return (mt_rand(0, $variance * 200) - $variance * 100) *0.0001; } The value returned can be then be multiplied against another value and added to itself. This can be useful if one needs to take crime exp and randomize it: $crime_exp = 100; $variance = deviation(5); $crime_exp = $crime_exp + $crime_exp * $variance; Sample code: <?php function deviation($variance) { return (mt_rand(0, $variance * 200) - $variance * 100) *0.0001; } for ($x = 1; $x <= 30; $x++ ) { $crime_exp = 100; $variance = deviation(5); $crime_exp = $crime_exp + $crime_exp * $variance; echo $crime_exp; echo "\n"; } Sample output: 104.12 99.79 95.94 101.6 99.02 104.06 95.01 95.56 95.04 97.4 101.99 95.35 95.62 104.19 100.49 100.25 98.19 101.89 98.05 104.86 99.58 99.24 104 101.17 104.99 98.42 100 95.33 95.82 103.02 Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.