How to create random positive or negative decimal place?

How can I recover a random decimal from -0.0010 to 0.0010 using php rand()or some other method?

+3
source share
5 answers

Divide rand()by the maximum random number, 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;
?>
+5
source

.

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

rand(), , . -1, +1. 0 +/- .

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

LOT , , , . (50 000 ), 0,0004 , . , , , , , - .

:

$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.";
+1

-0.001 +0.001

$random = ((rand()*(0.002/getrandmax()))-0.001)
// or without paranthesis:
$random = rand()*0.002/getrandmax()-0.001
0
$randselect=rand(0,(array_sum($adarray)*100000000));
$cumilativevalue=0;
foreach ($adarray as $key => $value) {
$cumilativevalue=$cumilativevalue+$value*100000000;
    if($randselect<$cumilativevalue){$selectedad=$key;break;}
}
0

Source: https://habr.com/ru/post/1753757/


All Articles