在Python中,使用SciPy,我需要找到函数的最大值Q*((1+y)*2-3*Q-0.1)-y**2
给定限制(1-z)*(Q*((1+y)*2-3*Q-0.1))-y**2=0
。对于z
,我想输入一些值来查找在z
的值下最大化函数的参数。
我尝试了很多方法来使用SciPy优化功能,但我无法弄清楚如何去做。我使用WolframAlpha成功地做到了这一点,但这并没有为我提供对此后续问题的回答。
尝试:
from scipy.optimize import minimize
def equilibrium(z):
#Objective function
min_prof = lambda(Q,y): -1*(Q*((1+y)*2-3*Q-0.1)-y**2)
#initial guess
x0 = (0.6,0.9)
#Restriction function
cons = ({'type': 'eq', 'fun': lambda (Q,y): (1-z)*(Q*((1+y)*2-3*Q-0.1))-y**2})
#y between 0 and 1, Q between 0 and 4
bnds = ((0,4),(0,1))
res = minimize(min_prof,x0, method='SLSQP', bounds=bnds ,constraints=cons)
return res.x
from numpy import arange
range_z = arange(0,1,0.001)
print equilibrium(range_z)
错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-20-527013574373> in <module>()
21 range_z = arange(0,1,0.01)
22
---> 23 print equilibrium(range_z)
<ipython-input-20-527013574373> in equilibrium(z)
14 bnds = ((0,4),(0,1))
15
---> 16 res = minimize(min_prof,x0, method='SLSQP', bounds=bnds ,constraints=cons)
17
18 return res.x
/Users/Joost/anaconda/lib/python2.7/site-packages/scipy/optimize/_minimize.pyc in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
456 elif meth == 'slsqp':
457 return _minimize_slsqp(fun, x0, args, jac, bounds,
--> 458 constraints, callback=callback, **options)
459 elif meth == 'dogleg':
460 return _minimize_dogleg(fun, x0, args, jac, hess,
/Users/Joost/anaconda/lib/python2.7/site-packages/scipy/optimize/slsqp.pyc in _minimize_slsqp(func, x0, args, jac, bounds, constraints, maxiter, ftol, iprint, disp, eps, callback, **unknown_options)
324 + 2*meq + n1 + ((n+1)*n)//2 + 2*m + 3*n + 3*n1 + 1
325 len_jw = mineq
--> 326 w = zeros(len_w)
327 jw = zeros(len_jw)
328
ValueError: negative dimensions are not allowed
答案 0 :(得分:0)
您需要一次评估一个z
的功能。使代码工作的最小修改如下:
print [equilibrium(z) for z in z_range]
在当前代码中,描述约束的函数返回一个向量而不是标量,这会导致错误消息。
您可能会注意到您的问题可以通过分析解决,而不是在数字上进行优化:
a = 0.1
Q = (6-3*a+3**.5 *(4-4*a+a**2-4*z+4*a*z-a**2 *z)**.5)/(6*(2+z))
y = Q*(1-z)+(Q*(-1+z)*(-2+a+Q*(2+z)))**.5
您可以对此进行测试并说服自己,它会提供与数值优化相同的结果(最高数值精度)。 (我已经测试了z = 0.745 - 您需要检查二阶导数以选择正确的最大值。但这是可行的。)