窮舉搜尋法
你已經套用了目標函式並視覺化結果;不過,先前只能透過觀察圖形來大致判斷最佳值。更精確的作法是使用窮舉搜尋法。
你再次為一家出版與印刷雜誌的媒體公司工作,但這次要找的是如何讓利潤最大化,而非讓成本最小化。請記得,利潤與數量的單位皆為千,因此 q 為 1 代表 1,000 本雜誌,而利潤為 5 代表 $5,000。
我們已提供與前一題相同的 quantity 陣列,以及要最佳化的 profit() 函式。
已為你匯入 numpy 並命名為 np。
本練習屬於課程
Python 最佳化入門
練習說明
- 使用提供的
profit()函式計算每個數量的利潤,儲存為profits。 - 用適當的陣列方法找出最大利潤,儲存為
max_profit。 - 先將最大利潤的索引儲存為
max_index,再用它來擷取quantity,以找出讓利潤最大的最佳數量。 - 透過完成 f-string 列印結果,記得將利潤與數量都乘以
1000。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Calculate the profit for every quantity
profits = ____
# Find the maximum profit
max_profit = ____
# Find the optimal quantity
max_profit_ind = ____
optimal_quantity = ____
# Print the results
print(f"You need to print {____} magazines to make the maximum profit of ${____}.")