Jump to content
MakeWebGames

Recommended Posts

Posted

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...