views:

469

answers:

2

Hi,

I have a simple piece of PHP code which requires a random number to be created. However, even though the input is always positive, it sometimes returns a negative output.

Here's my debug code:

$debt = rand($this->gdp * 0.02, $this->gdp * 0.17);
echo "<p>GDP: ".$this->gdp." rand(".$this->gdp * 0.02."  , ".$this->gdp * 0.17.") = <strong>".$debt."</strong></p>";

Here's an example output:

GDP: 219254674605 rand(4385093492.1 , 37273294682.85) = 75276999

GDP: 345015694865 rand(6900313897.3 , 58652668127.05) = -1636353016

GDP: 90445390920 rand(1808907818.4 , 15375716456.4) = -165604705

GDP: 3412849650 rand(68256993 , 580184440.5) = 347516196

GDP: 2939111315 rand(58782226.3 , 499648923.55) = 119181875

GDP: 26369065 rand(527381.3 , 4482741.05) = 3632416

GDP: 215838135 rand(4316762.7 , 36692482.95) = 28784811

GDP: 511763530 rand(10235270.6 , 86999800.1) = 39954394

GDP: 42416245 rand(848324.9 , 7210761.65) = 3974882

GDP: 75090235 rand(1501804.7 , 12765339.95) = 5201966

So why would a rand() of two positive numbers give a negative return?

Any help would be much appreciated!

+10  A: 
Joey
Consider using mt_rand() instead
Psytronic
Psytronic: which changes *what* exactly? http://de.php.net/manual/en/function.mt-rand.php shows that `mt_rand` also uses `int` arguments.
Joey
I was just going on the note underneath the rand description:Note: On some platforms (such as Windows), getrandmax() is only 32768. If you require a range larger than 32768, specifying min and max will allow you to create a range larger than this, or consider using mt_rand() instead.
Psytronic
Thanks for a great answer :)
Philip Morton
Psytronic: Ok, my final option which may solve the OP's problems uses mt_rand() just to be sure. :-)
Joey
+1  A: 

Rand takes as arguments, and returns, integers. Integers (in PHP) usually have a maximum range of 2**32.

Your double arguments are larger than this, causing an integer overflow when they are converted to integers.

gnud