我用optimize.root
来寻找方程组的数值解。我需要将每个条件表示为一个单独的函数,还需要将参数传递给某些条件。但是,optimize.root
似乎只有在目标函数本身内而不是在目标函数调用的单独函数中进行计算时,才能正确传递参数。在
以下代码复制了该问题:
# Conditions to be solved
def fSSBj(inp):
return (0.5*inp[1])/(1+inp[1])-0.9*inp[0]
def fSSBJ(inp):
return inp[0]-inp[2]*inp[1]
# Objective function with conditions inserted directly
def objFunc1(inp,pM):
out = empty(2)
out[0] = (0.5*inp[1])/(1+inp[1])-0.9*inp[0]
out[1] = inp[0]-pM*inp[1]
return out
# Objective function that calls the functions with the conditions
def objFunc2(inp,pM):
out = empty(2)
out[0] = fSSBj(inp+[pM])
out[1] = fSSBJ(inp+[pM])
return out
请注意,两个目标函数使用相同的输入;它们也给出相同的输出:
^{pr2}$这两个命令都会返回
[-0.65 0.8 ]
但是,问题是,以下两个命令给出的结果截然不同:
Out1 = optimize.root(objFunc1, [1.0,1.0], args = (0.2), method='hybr')
Out2 = optimize.root(objFunc2, [1.0,1.0], args = (0.2), method='hybr')
第一个很好;第二个给出一个错误消息(Index is out of bounds
)。optimize.root
如何将参数传递给函数会有问题吗?在
这对我来说是个问题,因为(1)我有不同的条件集要解决;(2)我需要用一阶导数来构造雅可比函数。基于这两个原因,我使用SymPy的lambdify
函数来生成函数及其导数,并将它们包含在目标函数中。在
我假设
numpy
将您的输入列表转换为ndarray
。在不幸的是
因此,您将得到一个
IndexError
。在这就是我需要的暗示!当我使用
numpy.concatenate
时,它是有效的。工作代码如下:相关问题 更多 >
编程相关推荐