2012-04-05 58 views
1

FsolveScipy似乎是這個的合適人選,我只需要幫助動態地傳遞方程。我很欣賞任何想法。求解python中的非線性方程的動態數量

通過動態我的意思是方程的數目從一個運行的不同而不同,例如一種情況下我有:

alpha*x + (1-alpha)*x*y - y = 0 
beta*x + (1- beta)*x*z - z = 0 
A*x + B*y + C*z = D 

和另一種情況下我有:

alpha*x + (1-alpha)*x*y - y = 0 
beta*x + (1- beta)*x*z - z = 0 
gama*x + (1 -gama)*x*w - w =0 
A*x + B*y + C*z + D*w = E 

alphabetaAB,C,DE都是常數。 x,y,zw是變量。

+0

我打了SciPy的,但我沒有成功與活力的部分。你基本上需要事先爲你的方程式定義函數,這不是我想要的。然後我在R.中研究了BBsolve,似乎解決了我尋求的問題。 – pouria3 2012-04-10 06:03:37

回答

1

我還沒有使用Fsolve自己,但根據它的文檔它需要一個可調用的函數。 像這樣的東西可以處理多個變量數量未知的函數。請記住,這裏的參數必須正確排序,但每個函數都只需要一個列表。

def f1(argList): 
    x = argList[0] 
    return x**2 
def f2(argList): 
    x = argList[0] 
    y = argList[1] 
    return (x+y)**2 
def f3(argList): 
    x = argList[0] 
    return x/3 

fs = [f1,f2,f3] 
args = [3,5] 
for f in fs: 
    print f(args) 

對於Fsolve,你可以嘗試這樣的事情(未經測試):

def func1(argList, constList): 
    x = argList[0] 
    y = argList[1] 
    alpha = constList[0] 
    return alpha*x + (1-alpha)*x*y - y 
def func2(argList, constList): 
    x = argList[0] 
    y = argList[1] 
    z = argList[2] 
    beta = constList[1] 
    return beta*x + (1- beta)*x*z - z 
def func3(argList, constList): 
    x = argList[0] 
    w = argList[1] ## or, if you want to pass the exact same list to each function, make w argList[4] 
    gamma = constList[2] 
    return gama*x + (1 -gama)*x*w - w 
def func4(argList, constList): 

    return A*x + B*y + C*z + D*w -E ## note that I moved E to the left hand side 


functions = [] 
functions.append((func1, argList1, constList1, args01)) 
# args here can be tailored to fit your function structure 
# Just make sure to align it with the way you call your function: 
# args = [argList, constLit] 
# args0 can be null. 
functions.append((func1, argList2, constList2, args02)) 
functions.append((func1, argList3, constList3, args03)) 
functions.append((func1, argList4, constList4, args04)) 

for func,argList, constList, args0 in functions: ## argList is the (Vector) variable you're solving for. 
    Fsolve(func = func, x0 = ..., args = constList, ...) 
+0

非常感謝您的幫助和洞察力。我的問題之一是,我不知道我有多少個方程式,所以我不能真正定義它們的功能。 – pouria3 2012-04-05 18:22:25

+0

從哪裏獲得方程列表的來源是什麼?你可以動態地定義它們並追加到列表中,但是這將專門爲方程式的源格式量身定製 – 2012-04-05 19:44:40

+0

@ pouria3在python中,幾乎所有事情都是在運行時發生的。在運行時你應該知道你擁有多少個equi,因爲你有*他們。您不必事先知道* * – Simon 2012-04-06 09:05:53