python - 使用 Python(spicy.optimize)进行优化 - 约束问题
问题描述
我正在尝试使用下面提供的代码优化数学问题。代码运行没有错误,但它在不考虑约束的情况下打印结果。p1 和 p2 是工厂的产品,m1、m2、m3 是生产所需的原材料(我提供这条信息以防有人想知道 m1、m2、m3 和 p1、p2 之间的方程式代表什么)。知道可能出了什么问题吗?
import numpy as np
from scipy.optimize import minimize
earnings_p1 = 150
earnings_p2 = 175
costs_m1 = 10
costs_m2 = 17
costs_m3 = 25
def objective(x):
quantity_p1 = x[0]
quantity_p2 = x[1]
quantity_m1 = 2 * quantity_p1 + 1 * quantity_p2
quantity_m2 = 5 * quantity_p1 + 3 * quantity_p2
quantity_m3 = 0 * quantity_p1 + 4 * quantity_p2
total_costs = quantity_m1 * costs_m1 + quantity_m2 * costs_m2 + quantity_m3 * costs_m3
total_earnings = quantity_p1 * earnings_p1 + quantity_p2 * earnings_p2
total_profit = total_earnings - total_costs
return -total_profit
def constraint1(x):
quantity_p1 = x[0]
quantity_p2 = x[1]
quantity_m1 = 2 * quantity_p1 + 1 * quantity_p2
return 100 - quantity_m1
def constraint2(x):
quantity_p1 = x[0]
quantity_p2 = x[1]
quantity_m2 = 5 * quantity_p1 + 3 * quantity_p2
return 80 - quantity_m2
def constraint3(x):
quantity_p1 = x[0]
quantity_p2 = x[1]
quantity_m3 = 0 * quantity_p1 + 4 * quantity_p2
return 150 - quantity_m3
cons1 = ({'type': 'ineq', 'fun': constraint1})
cons2 = ({'type': 'ineq', 'fun': constraint2})
cons3 = ({'type': 'ineq', 'fun': constraint3})
cons = [cons1, cons2, cons3]
quantity_p1_guess = 10
quantity_p2_guess = 20
x0 = np.array([quantity_p1_guess, quantity_p2_guess])
solution = minimize(objective, x0, method='SLSQP', constraints=cons, options={'disp': True})
print(solution)
解决方案
推荐阅读
- excel - 如何在旧版本的 Excel 中替换 TEXTJOIN()?
- mysql - GROUP CONCAT 和 LEFT OUTER JOIN 拆分
- lead - TikTok 潜在客户生成 - 错误轮询下载任务
- c++ - 无法使用 cv::VideoCapture 打开 .mp4
- angular - Autocomplet 不能在 Angular 中同时使用两个值?
- jquery - 如何在 sub-html 页面中调用 Jquery 代码?
- python - 根据python和selenium中的动态值选择字典名称
- arduino - 从jetson发送到arduino的数据
- java - Java 类不是使用 maven-jaxb2-plugin 从 wsdl 文件生成的
- javascript - 视图之间的转换