首页 > 解决方案 > 使用 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)

标签: pythonoptimizationscipymathematical-optimization

解决方案


推荐阅读