[英]Random Float against an specific amount with 100 days php
我正在尝试针对 100 天的“100”数量生成随机值。 我正在用 for 循环尝试这种方式:
$total_days = 100;
$total_amount = 100;
$arr = array();
for($i = 0; $i < $total_days; ++$i)
{
$arr[] = rand(0.0, 1000.0);
}
$actual_sum = array_sum($arr);
for($i = 0; $i < $total_days; ++$i)
{
$arr[$i] *= $total_amount /$actual_sum;
//echo $arr[$i]."<BR><BR>";
$value = $arr[$i];
$genpackageroi = array(
'userid' => $userid,
'pkgid' => $pkgid,
'pkgcount' => $pkcount,
'amount' => $value,
'created_at' => $created_at,
'updated_at' => $updated_at,
);
DB::table('genpackageroi')->insert($genpackageroi);
}
随机生成的值就像 0.1245444 OR 1.1245545,十进制后的很多数字。 虽然我只是希望它以浮点值生成,例如 1.21、0.10、2.25,像这样。 我有可能这样做吗?
但我想以整数生成随机数。 因为如果我们将生成的随机数相加,它与生成所有随机数后的实际数量不匹配。 就像如果我生成数量为 100 的随机数,那么所有生成的随机数的总和应该是 100。这就是我真正想要的。
我从您的陈述中收集到的是,您需要 100 个带有 2 个小数位的浮点数,并且所有这些数字的总和应为 100。
这当然不是最干净的解决方案,但这里有:
$total_days = 100;
$total_amount = 100;
$arr = array();
for($i = 0; $i < $total_days; ++$i)
{
$arr[] = rand(0.0, 1000.0);
}
$actual_sum = array_sum($arr);
for($i = 0; $i < $total_days; ++$i)
{
$y = $arr[$i] * ($total_amount /$actual_sum);
$arr[$i] = round($y, 2); //round the numbers to 2 dp. Sum of all numbers could be greater than 100.
}
//hack, logic explained below
$maxElementKeys = array_keys($arr, max($arr)); //get max element's key
unset($arr[$maxElementKeys[0]]); //remove the max element from array, now the array contains 99 elements
$arr = array_values($arr); //rebase the keys
for($i = 0; $i < $total_days; ++$i)
{
if($i < ($total_days - 1) )
$value = $arr[$i];
else
$value = $total_amount - array_sum($arr); //to get the 100th number, subtract from 100 to ensure the total always adds up to 100
$genpackageroi = array(
'userid' => $userid,
'pkgid' => $pkgid,
'pkgcount' => $pkcount,
'amount' => $value,
'created_at' => $created_at,
'updated_at' => $updated_at,
);
DB::table('genpackageroi')->insert($genpackageroi);
}
这里的逻辑是将所有数字四舍五入到 2dps。 在大多数情况下,总数会超过 100 几个 dps。 接下来,获取数组中的最大随机数并将其从数组中移除,使其成为包含 99 个元素的数组。 删除最大数以确保新数组的总和保持在 100 以下。因此,要获得第 100 个元素,请获取新数组的总和并从 100 中减去该值。现在,所有元素的总和数组和刚刚计算的第 100 个元素的总和应该正好是 100,失败的可能性可以忽略不计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.