2015-04-16 65 views
1

我正試圖找到一個很好的方法來解決python非線性超定系統。我在這裏查看優化工具http://docs.scipy.org/doc/scipy/reference/optimize.nonlin.html,但我無法弄清楚如何使用它們。我到目前爲止是使用python解決非線性超定系統

#overdetermined nonlinear system that I'll be using 
''' 
a = cos(x)*cos(y)       
b = cos(x)*sin(y)       
c = -sin(y)         
d = sin(z)*sin(y)*sin(x) + cos(z)*cos(y)  
e = cos(x)*sin(z)       
f = cos(z)*sin(x)*cos(z) + sin(z)*sin(x)  
g = cos(z)*sin(x)*sin(y) - sin(z)*cos(y)  
h = cos(x)*cos(z) 
a-h will be random int values in the range 0-10 inclusive 
''' 
import math 
from random import randint 
import scipy.optimize 

def system(p): 
    x, y, z = p 
    return(math.cos(x)*math.cos(y)-randint(0,10), 
      math.cos(x)*math.sin(y)-randint(0,10), 
      -math.sin(y)-randint(0,10), 
      math.sin(z)*math.sin(y)*math.sin(x)+math.cos(z)*math.cos(y)-randint(0,10), 
      math.cos(x)*math.sin(z)-randint(0,10), 
      math.cos(z)*math.sin(x)*math.cos(z)+math.sin(z)*math.sin(x)-randint(0,10), 
      math.cos(z)*math.sin(x)*math.sin(y)-math.sin(z)*math.cos(y)-randint(0,10), 
      math.cos(x)*math.cos(z)-randint(0,10)) 

x = scipy.optimize.broyden1(system, [1,1,1], f_tol=1e-14) 

你能幫我一下嗎?

回答

2

如果我理解你的話,你想找到方程f(x) = b的非線性系統的近似解,其中b是包含隨機值b=[a,...,h]的向量。

爲了做到這一點,您首先需要從system函數中刪除隨機值,否則在每次迭代中求解器都會嘗試求解不同的方程組。此外,我認爲基本Broyden方法僅適用於具有與方程式一樣多的未知數的系統。或者,您可以使用scipy.optimize.leastsq。一個可能的解決方案如下所示:

# I am using numpy because it's more convenient for the generation of 
# random numbers. 
import numpy as np 
from numpy.random import randint 
import scipy.optimize 

# Removed random right-hand side values and changed nomenclature a bit. 
def f(x): 
    x1, x2, x3 = x 
    return np.asarray((math.cos(x1)*math.cos(x2), 
         math.cos(x1)*math.sin(x2), 
         -math.sin(x2), 
         math.sin(x3)*math.sin(x2)*math.sin(x1)+math.cos(x3)*math.cos(x2), 
         math.cos(x1)*math.sin(x3), 
         math.cos(x3)*math.sin(x1)*math.cos(x3)+math.sin(x3)*math.sin(x1), 
         math.cos(x3)*math.sin(x1)*math.sin(x2)-math.sin(x3)*math.cos(x2), 
         math.cos(x1)*math.cos(x3))) 

# The second parameter is used to set the solution vector using the args 
# argument of leastsq. 
def system(x,b): 
    return (f(x)-b) 

b = randint(0, 10, size=8) 
x = scipy.optimize.leastsq(system, np.asarray((1,1,1)), args=b)[0] 

我希望這對您有所幫助。但是請注意,找到解決方案的可能性非常小,特別是在間隔[0,10]中生成隨機整數,而f的範圍限制爲[-2,2]時

相關問題