2015-03-03 27 views
0

为什么下面的代码返回一个ValueError?Python fsolve ValueError

from scipy.optimize import fsolve 
import numpy as np 

def f(p,a=0): 
    x,y = p 
    return (np.dot(x,y)-a,np.outer(x,y)-np.ones((3,3)),x+y-np.array([1,2,3])) 

x,y = fsolve(f,(np.ones(3),np.ones(3)),9) 


ValueError: setting an array element with a sequence. 
+0

可能重复:设定的数组元素与序列。此消息可能会显示没有序列的现有?](http://stackoverflow.com/questions/13310347/numpy-valueerror-setting-an-array-element-with-a-sequence-this-message-may-app ) – 2015-03-03 09:53:44

+0

该函数本身不会导致任何问题,我只是不明白为什么fsolve不起作用。 – laditet 2015-03-03 09:56:35

+2

函数中的参数'p'和初始猜测必须是单个数组,而不是两个数组的元组 – 2015-03-03 10:06:43

回答

1

这里的基本问题是,你的函数f不能满足工作需要fsolve的标准。这些标准被描述为in the documentation - 虽然可以说不是很清楚。

,你需要了解的特定事情是:

  1. 输入到将要解决的必须是n维向量的函数(在该文档中被称为ndarray) ,所以你想要的值xf(x, *args) = 0的解决方案。
  2. f的输出必须相同形状作为x输入到f

目前,您的函数需要一个2构件的1x3-arraystuple(在p)和一个固定的标量偏移(在a)。它返回一个3个成员tuple的类型(scalar,3x3 array,1x3 array

正如你所看到的,条件1和2都不符合。

很难告诉你如何解决这个问题,而不是完全确定你正试图解决的方程。看来你试图解决一些特定的方程f(x,y,a) = 0xyx0 = (1,1,1)y0 = (1,1,1)a = 9作为一个固定值。您威力能够通过传递xy级联做到这一点(例如,通过在p0 = (1,1,1,1,1,1)和功能使用x=p[:3]y = p[3:]但你必须修改你的函数输出x和y连接成一个6维向量同样,这取决于你正在解决的确切功能,我无法从现有的f(即基于点积,外积和基总和元组)。

注意的输出来解决这一问题那些你不传入向量的参数(例如你的案例中的a)将被视为固定值,不会作为优化的一部分而变化,或作为任何解决方案的一部分返回。


注对于那些谁喜欢完整的故事...

As the docs say:

fsolve is a wrapper around MINPACK’s hybrd and hybrj algorithms.

如果我们看一下MINPACK hybrd documentation,输入和输出向量的条件更明确规定。请参阅下面的相关部分(为了清晰,我已经删除了一些内容 - 用...表示 - 和添加的注释表明输入和输出必须是相同的形状 - 以<表示 - )[numpy的ValueError异常的

1 Purpose.

The purpose of HYBRD is to find a zero of a system of N non- linear functions in N variables by a modification of the Powell hybrid method. The user must provide a subroutine which calcu- lates the functions. The Jacobian is then calculated by a for- ward-difference approximation.

2 Subroutine and type statements.

SUBROUTINE HYBRD(FCN,N,X, ... 

...

FCN is the name of the user-supplied subroutine which calculates the functions. FCN must be declared in an EXTERNAL statement in the user calling program, and should be written as follows.

SUBROUTINE FCN(N,X,FVEC,IFLAG) 
INTEGER N,IFLAG 
DOUBLE PRECISION X(N),FVEC(N) <-- input X is an array length N, so is output FVEC 
---------- 
CALCULATE THE FUNCTIONS AT X AND 
RETURN THIS VECTOR IN FVEC. 
---------- 
RETURN 
END 

N is a positive integer input variable set to the number of functions and variables.

X is an array of length N. On input X must contain an initial estimate of the solution vector. On output X contains the final estimate of the solution vector.