How to generate a random positive or negative deci

2019-06-28 00:13发布

How can I regenerate random decimal from -0.0010 to 0.0010 with php rand() or some other method?

标签: php random
5条回答
欢心
2楼-- · 2019-06-28 00:22

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
查看更多
女痞
3楼-- · 2019-06-28 00:38

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.";
查看更多
该账号已被封号
4楼-- · 2019-06-28 00:40
$randselect=rand(0,(array_sum($adarray)*100000000));
$cumilativevalue=0;
foreach ($adarray as $key => $value) {
$cumilativevalue=$cumilativevalue+$value*100000000;
    if($randselect<$cumilativevalue){$selectedad=$key;break;}
}
查看更多
不美不萌又怎样
5楼-- · 2019-06-28 00:42

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;
?>
查看更多
Explosion°爆炸
6楼-- · 2019-06-28 00:42

.

$val = (rand(0,20)-10)/10000;
查看更多
登录 后发表回答