2015-03-03 73 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.