PHP generate a random minus or plus percentage of a given value

前提是你 提交于 2020-01-07 05:46:07

问题


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);


来源:https://stackoverflow.com/questions/17840009/php-generate-a-random-minus-or-plus-percentage-of-a-given-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!