穷举搜索法
您已经应用了目标函数并可视化了结果;不过,您只能通过查看图形来大致判断最优值。更精确的做法是使用穷举搜索法。
您仍在一家出版并印刷杂志的媒体公司工作,这一次,您将发现如何最大化利润,而不是最小化成本。回顾一下,利润和数量的单位都是以千为单位,因此 q 为 1 表示 1000 本杂志,利润为 5 表示 $5000。
上一练习中的同一个 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 ${____}.")