在Python中使用Lagrange乘数的Numpy Arange错误 [英] Numpy arange error with Lagrange Multiplier in Python

查看:113
本文介绍了在Python中使用Lagrange乘数的Numpy Arange错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Lagrange乘数来优化函数,并且试图遍历该函数以获取数字列表,但是出现错误

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.    

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

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

推荐答案

首先,检查func = fsolve()

First, check func = fsolve()

第二,print(func([1,1,0]))`-结果不是数字([2 2 2 2 2 2 2 2 2 2]),因为"n"是列表.如果您想重复n次尝试:

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

这篇关于在Python中使用Lagrange乘数的Numpy Arange错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆