亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

100 天 php 針對特定金額的隨機浮動

100 天 php 針對特定金額的隨機浮動

PHP
慕哥9229398 2023-12-15 10:37:34
我正在嘗試針對“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 或 1.1245545,小數點后有很多數字。雖然我只想以浮點值生成它,例如 1.21、0.10、2.25 等。我可以這樣做嗎?
查看完整描述

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,失敗的可能性可以忽略不計。


查看完整回答
反對 回復 2023-12-15
  • 1 回答
  • 0 關注
  • 180 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號