开发者

How to generate a random positive or negative decimal?

How ca开发者_JAVA技巧n I regenerate random decimal from -0.0010 to 0.0010 with php rand() or some other method?


Divide rand() by the maximum random numer, multiply it by the range and add the starting number:

<?php
  // rand()/getrandmax() gives a float number between 0 and 1
  // if you multiply it by 0.002 you'll get a number between 0 and 0.002
  // add the starting number -0.001 and you'll get a number between -0.001 and 0.001

  echo rand()/getrandmax()*0.002-0.001;
?>


.

$val = (rand(0,20)-10)/10000;


This uses two rand() calls but I think that the readability makes up for it tenfold. The first part makes either a -1 or +1. The second part can be anything between 0 and your limit for +/- numbers.

$rand = (rand(0,1)*2-1)*rand(0, 100);
echo $rand;

Unless you require LOTs of random numbers in a gigantic loop, you probably won't even notice the speed difference. I ran some tests (50.000 iterations) and it came up to around 0.0004 milliseconds to get a random number by my function. The alternatives are around half that time, but again, unless you are inside a really big loop, you are probably better of optimizing somewhere else.

Speed testing code:

$start = microtime();
$loopCount = 50000;
for($i=0;$i<$loopCount;$i++)
{
    (0*2-1)*rand(0, 100);
}
$end = microtime();

echo "Timing: ", ((($end-$start)*1000.0)/((float)$loopCount)), " milliseconds.";


This will return any possible number between -0.001 and +0.001

$random = ((rand()*(0.002/getrandmax()))-0.001)
// or without paranthesis:
$random = rand()*0.002/getrandmax()-0.001


$randselect=rand(0,(array_sum($adarray)*100000000));
$cumilativevalue=0;
foreach ($adarray as $key => $value) {
$cumilativevalue=$cumilativevalue+$value*100000000;
    if($randselect<$cumilativevalue){$selectedad=$key;break;}
}


Random float with one decimal between -1,1

$random = round((rand(0,1) - floatVal('0.'.rand(0,9).rand(0,9))), 1);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜