gpt4 book ai didi

python - Python 中拉格朗日乘数的 Numpy arange 错误

转载 作者:行者123 更新时间:2023-12-01 03:23:50 26 4
gpt4 key购买 nike

我尝试使用拉格朗日乘子来优化函数,并且尝试循环该函数以获取数字列表,但是出现错误

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)

如果有帮助,我们将不胜感激,非常感谢

最佳答案

首先,检查 func = fsolve()

第二, print(func([1,1,0]))` - 结果不是数字 ([2 2 2 2 2 2 2 2 2]),因为“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)))

关于python - Python 中拉格朗日乘数的 Numpy arange 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41634979/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com