Q:

Numpy arange error with Lagrange Multiplier in Python

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

A:

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

