最佳化成本
現在要用你先前建立的函式來最佳化生產成本。我們的目標是讓平均利潤最大化。不過,利潤受到多個因素影響,而我們只能控制成本。因此,我們可以模擬其他因素的不確定性,並調整成本,觀察利潤會如何變動。
因為你管理著一個小型玉米農場,你可以自行決定成本範圍,從 $100 到 $5,000。你想要選出能帶來最高平均利潤的成本。在本練習中,我們會對每個成本水準進行多次模擬,並計算其平均值。接著,我們會挑出能產生最高平均利潤的成本。完成後,你就會有一個可用於商業決策、選取最佳輸入參數的框架。
本練習屬於課程
Python 的統計模擬
練習說明
- 初始化空的字典
results。 - 對每個成本水準,使用已預先載入的
profits()函式模擬利潤,並將結果加入tmp_profits。 - 將各成本水準的
tmp_profits平均值儲存到字典results中。 - 將
results丟進列表生成式,找出擁有最高平均利潤的成本水準cost_max。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Initialize results and cost_levels variables
sims, results = 1000, ____
cost_levels = np.arange(100, 5100, 100)
# For each cost level, simulate profits and store mean profit
for cost in cost_levels:
tmp_profits = []
for i in range(sims):
tmp_profits.append(____)
results[cost] = np.mean(____)
# Get the cost that maximizes average profit
cost_max = [x for x in ____.keys() if ____[x] == max(____.values())][0]
print("Average profit is maximized when cost = {}".format(cost_max))