PHP generate a random minus or plus percentage of

2019-09-11 03:38发布

问题:

I have a value, lets say its 1000. Now I have to generate a random minus or plus percentage of 1000. In particular I have to generate or a -20% of 1000 or a +20% of 1000 randomly.

I tried using rand() and abs() but with no success..

Is there a way in PHP to achieve the above?

回答1:

A bit of basic mathematics

$number = 1000;
$below = -20;
$above = 20;
$random = mt_rand(
    (integer) $number - ($number * (abs($below) / 100)),
    (integer) $number + ($number * ($above / 100))
);


回答2:

rand(0, 1) seems to work fine for me. Maybe you should make sure your percentage is in decimal format.

<?php
$val = 10000;
$pc = 0.2;
$result = $val * $pc;
if(rand(0, 1)) echo $result; else  echo -$result;
if(rand(0, 1)) echo $result; else  echo -$result;
if(rand(0, 1)) echo $result; else  echo -$result;
if(rand(0, 1)) echo $result; else  echo -$result;
if(rand(0, 1)) echo $result; else  echo -$result;
?>


回答3:

$number = 10000;
$percent = $number*0.20;
$result =  (rand(0,$percent)*(rand(0,1)*2-1));

echo $result;

Or if you want some sort of running balance type thing....

function plusminus($bank){
 $percent = $bank*0.20;
 $random = (rand(0,$percent)*(rand(0,1)*2-1));
 return $bank + $random;
}

$new =  plusminus(10000);
$new = plusminus($new);
echo $new."<br>";
$new = plusminus($new);
echo $new."<br>";
$new = plusminus($new);
echo $new."<br>";
$new = plusminus($new);
echo $new."<br>";
$new = plusminus($new);
echo $new."<br>";
$new = plusminus($new);


标签: php random