Skip to content Skip to sidebar Skip to footer

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

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

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

defdfunc(X,n):
    dLambda = np.zeros(len(X))
    h = 1e-3
    r = 0for i inrange(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)))

Post a Comment for "Numpy Arange Error With Lagrange Multiplier In Python"