Numpy arange error with Lagrange Multiplier in Python

一笑奈何 提交于 2020-01-15 11:45:07

问题


I try to use Lagrange multiplier to optimize a function, and I am trying to loop through the function to get a list of number, however I got the error

ValueError: setting an array element with a sequence.    

Here is my code, where do I go wrong? If the n is not an array I can get the result correctly though

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)

Helps would be appreciated, thank you very much


回答1:


First, check func = fsolve()

Second, print(func([1,1,0]))` - result in not number ([2 2 2 2 2 2 2 2 2]), beause "n" is list. if you want to iterate n try:

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)))


来源:https://stackoverflow.com/questions/41634979/numpy-arange-error-with-lagrange-multiplier-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!