我用PuLP解决了一些具有约束、uper和下界的极小化问题。它很简单,很干净。
但是我只需要使用Scipy和Numpy模块。
我在读:http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html
多元标量函数的约束极小化
但我有点迷路了..。一些好的灵魂可以张贴一个小的例子,像这个PuLP一个在西西?
提前谢谢。MM
from pulp import *
'''
Minimize 1.800A + 0.433B + 0.180C
Constraint 1A + 1B + 1C = 100
Constraint 0.480A + 0.080B + 0.020C >= 24
Constraint 0.744A + 0.800B + 0.142C >= 76
Constraint 1C <= 2
'''
...发布于 2013-10-29 17:50:36
请考虑以下几点:
import numpy as np
import scipy.optimize as opt
#Some variables
cost = np.array([1.800, 0.433, 0.180])
p = np.array([0.480, 0.080, 0.020])
e = np.array([0.744, 0.800, 0.142])
#Our function
fun = lambda x: np.sum(x*cost)
#Our conditions
cond = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 100},
{'type': 'ineq', 'fun': lambda x: np.sum(p*x) - 24},
{'type': 'ineq', 'fun': lambda x: np.sum(e*x) - 76},
{'type': 'ineq', 'fun': lambda x: -1*x[2] + 2})
bnds = ((0,100),(0,100),(0,100))
guess = [20,30,50]
opt.minimize(fun, guess, method='SLSQP', bounds=bnds, constraints = cond)应该注意的是,eq条件应该等于零,而对于任何大于零的值,ineq函数都将返回true。
我们获得:
status: 0
success: True
njev: 4
nfev: 21
fun: 97.884100000000345
x: array([ 40.3, 57.7, 2. ])
message: 'Optimization terminated successfully.'
jac: array([ 1.80000019, 0.43300056, 0.18000031, 0. ])
nit: 4重复检查均数:
output = np.array([ 40.3, 57.7, 2. ])
np.sum(output) == 100
True
round(np.sum(p*output),8) >= 24
True
round(np.sum(e*output),8) >= 76
True舍入来自于双点精度错误:
np.sum(p*output)
23.999999999999996https://stackoverflow.com/questions/19664865
复制相似问题