Python中使用Lagrange Multiplier的Numpy arange错误

时间:2017-01-13 12:45:46

标签: python numpy optimization

我尝试使用拉格朗日乘数来优化函数,我试图遍历函数来获取数字列表,但是我得到了错误

ValueError: setting an array element with a sequence.    

这是我的代码,我哪里出错了?如果n不是数组,我可以正确地得到结果

import numpy as np
from scipy.optimize import fsolve

n = np.arange(10000,100000,10000)

def func(X):
    x = X[0]
    y = X[1]
    L = X[2]
    return (x + y + L * (x**2 + y**2 - n))

def dfunc(X):
    dLambda = np.zeros(len(X))
    h = 1e-3
    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

X1 = fsolve(dfunc, [1, 1, 0])

print (X1)

非常感谢,非常感谢

1 个答案:

答案 0 :(得分:2)

首先,检查func = fsolve()

第二,打印(func([1,1,0]))` - 结果不是数字([2 2 2 2 2 2 2 2 2]),beause" n"是清单。如果你想迭代n尝试:

import numpy as np
from scipy.optimize import fsolve

n = np.arange(10000,100000,10000)

def func(X,n):
    x = X[0]
    y = X[1]
    L = X[2]
    return (x + y + L * (x**2 + y**2 - n))

def dfunc(X,n):
    dLambda = np.zeros(len(X))
    h = 1e-3
    r = 0
    for i in range(len(X)):
        dX = np.zeros(len(X))
        dX[i] = h
        dLambda[i] = (func(X+dX,n)-func(X-dX,n))/(2*h)
    return dLambda

for iter_n in n:
    print("for n = {0} dfunc = {1}".format(iter_n,dfunc([0.8,0.4,0.3],iter_n)))