拉格朗日乘数优化的误差

时间:2016-12-27 15:28:06

标签: python optimization

我试图使用拉格朗日乘数法最大化/最小化带有两个变量的函数,下面是我的代码

import numpy as np
from scipy.optimize import fsolve

Sa = 200
Sm = 100
n = 90
mu1 = 500
mu2 = 150
sigma1 = 25
sigma2 = 10
f = 0.9

def func(X):
    u1 = X[0]
    u2 = X[1]
    L = X[2] # this is the multiplier. lambda is a reserved keyword in python

    'function --> f(u1,u2) = u1**2 + u2**2'
    'constraint --> g(u1,u2) = (Snf/a)**1/b - n = 0'

    Snf = Sa/(1-Sm/(sigma1*u1 + mu1))
    a = (f*(sigma1*u1 + mu1)**2)/(sigma2*u2 + mu2)
    b = -1/3*(f*(sigma1*u1 + mu1))/(sigma2*u2 + mu2)
    return (u1**2+u2**2  - L * ((Snf/a)**1/b) - n)

def dfunc(X):
    dLambda = np.zeros(len(X))
    h = 1e-3 # this is the step size used in the finite difference.
    for i in range(len(X)):
        dX = np.zeros(len(X))
        dX[i] = h
        dLambda[i] = (func(X+dX)-func(X-dX))/(2*h);
    return dLambda

# this is the max
X1 = fsolve(dfunc, [1, 1, 0])
print (X1, func(X1))

# this is the min
X2 = fsolve(dfunc, [-1, -1, 0])
print (X2, func(X2))

当我尝试做一个简单的函数作为约束,如u1 + u2 = 4或u1 ^ 2 + u2 ^ 2 = 20时,它工作正常,但当我尝试我的实际约束函数时,它总是给出这个错误,有什么原因??谢谢你的帮助

C:\Python34\lib\site-packages\scipy\optimize\minpack.py:161:       
RuntimeWarning: The iteration is not making good progress, as measured by the 
improvement from the last five Jacobian evaluations.
warnings.warn(msg, RuntimeWarning)

0 个答案:

没有答案