我对Python还是很陌生,并试图找到与Excel Solver函数等效的Python。 假设我有以下输入:
import math
totalvolflow=150585.6894
gaspercentvol=0.1
prodmod=1224
blpower=562.57
powercons=6
gasvolflow=totalvolflow*gaspercentvol
quantity=math.ceil(gasvolflow/prodmod)
maxpercentvol=powercons*totalvolflow*prodmod/blpower
我想通过更改gaspercentvol找到maxpercentvol的最大值 具有以下约束:
quantity*powercon<blpower
任何帮助将不胜感激。
答案 0 :(得分:0)
根据:
maxpercentvol=powercons*totalvolflow*prodmod/blpower
maxpercentvol
为1,965,802.12765274,无论gaspercentvol
的值如何。
答案 1 :(得分:-1)
我不是一个精明的Excel用户,但是我的理解是Excel Solver是线性/非线性编程求解器,对吧?
在这种情况下,Python可以使用良好的优化库(例如SciPy's optimize)很好地服务。为了解决您的特定示例,您可以使用诸如:
import numpy as np
from scipy.optimize import minimize
import math
"""
x[0] = powercons
x[1] = totalvolflow
x[2] = prodmod
x[3] = blpower
x[4] = gaspercentvol
"""
def objective(x):
"""
-powercons*totalvolflow*prodmod/blpower
To maximize, we multiply our objective by -1
"""
return -1.0*(x[0]*x[1]*x[2]/x[3])
def constraint1(x):
"""
0 < blpower - quantity*powercon
minimize expects constrains to be greater or equal than zero
"""
return x[3] - (math.ceil(x[1]*x[4]/x[2])*x[0])
# Initial guess
n = 5
first_guess = np.zeros(n)
first_guess[0] = 6.0
first_guess[1] = 150585.6894
first_guess[2] = 1224
first_guess[3] = 562.57
first_guess[4] = 0.1
# constrains
constraint1_dict = {'type': 'ineq', 'fun': constraint1}
# bounds
problem_bounds = (
(6, 6),
(150585.6894, 150585.6894),
(1224, 1224),
(562.57, 562.57),
(0.05, 25)
)
# optimize
solution = minimize(
objective,
first_guess,
bounds=problem_bounds,
constraints=[constraint1_dict]
)
solution_values = solution.x
print(solution_values)