1 回答

TA貢獻(xiàn)1757條經(jīng)驗 獲得超7個贊
但我想生成整數(shù)的隨機數(shù)。因為它 生成所有隨機數(shù)后,劑量與實際數(shù)量不符 如果我們將生成的隨機數(shù)相加,則得到數(shù)字。就像如果我生成 數(shù)量為 100 的隨機數(shù),然后是所有生成的總和 隨機數(shù)應(yīng)該是 100。這就是我真正想要的。
我從你的陳述中得到的是,你想要 100 個帶有 2 位小數(shù)的浮點數(shù),所有這些數(shù)字的總和應(yīng)該為 100。
這當(dāng)然不是最干凈的解決方案,但這里是:
$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);
}
這里的邏輯是將所有數(shù)字四舍五入為 2dps。在大多數(shù)情況下,其總數(shù)會超過 100 幾個 dps。 接下來,獲取數(shù)組中最大的隨機數(shù),并將其從數(shù)組中刪除,使其成為包含 99 個元素的數(shù)組。刪除最大數(shù)是為了確保新數(shù)組的總和保持在 100 以下。因此,要獲取第 100 個元素,請獲取新數(shù)組的總和并從 100 中減去該值。現(xiàn)在,所有元素的總和數(shù)組的 和剛剛計算的第 100 個元素的總和應(yīng)該正好為 100,失敗的可能性可以忽略不計。
- 1 回答
- 0 關(guān)注
- 173 瀏覽
添加回答
舉報