1 回答

TA貢獻1757條經驗 獲得超7個贊
但我想生成整數的隨機數。因為它 生成所有隨機數后,劑量與實際數量不符 如果我們將生成的隨機數相加,則得到數字。就像如果我生成 數量為 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 中減去該值?,F在,所有元素的總和數組的 和剛剛計算的第 100 個元素的總和應該正好為 100,失敗的可能性可以忽略不計。
- 1 回答
- 0 關注
- 180 瀏覽
添加回答
舉報