0

我有一个值,假设它是 1000。现在我必须生成一个随机的负百分比或正百分比 1000。特别是我必须随机生成 1000 的 -20% 或 1000 的 +20%。

我尝试使用rand()abs()没有成功..

PHP中有没有办法实现上述目标?

4

4 回答 4

2

一点基础数学

$number = 1000;
$below = -20;
$above = 20;
$random = mt_rand(
    (integer) $number - ($number * (abs($below) / 100)),
    (integer) $number + ($number * ($above / 100))
);
于 2013-07-24T16:44:38.883 回答
0
$number = 10000;
$percent = $number*0.20;
$result =  (rand(0,$percent)*(rand(0,1)*2-1));

echo $result;

或者,如果您想要某种运行平衡类型的东西....

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);
于 2013-07-24T16:50:04.820 回答
0

rand(0, 1) 似乎对我来说很好用。也许你应该确保你的百分比是十进制格式。

<?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;
?>
于 2013-07-24T16:50:46.733 回答
0

我知道这现在真的很老了,但偶然发现它正在寻找类似的东西,我需要一个随机符号(+ 或 -),所以选择了一个随机布尔值:

<?php $sign = (rand(0,1) == 1) ? '+' : '-'; ?>

多亏了这个答案

所以我会选择这样的解决方案:

<?php

// Alter these as needed
$number = 1000;
$percentage = 20;

// Calculate the change
$change_by = $number * ($percentage / 100);

// Set a boolean at random
$random_boolean = rand(0,1) == 1; 

// Calculate the result where we are using plus if true or minus if false
$result = ($random_boolean) ? $number + $change_by : $number - $change_by;

// Will output either 1200 or 800 using these numbers as an example
echo $result;

?>
于 2020-02-07T11:35:39.840 回答