用python求解非线性超定系统

时间:2015-04-16 12:29:39

标签: python scipy

我试图找到一种用python解决非线性超定系统的好方法。我在这里查看了优化工具http://docs.scipy.org/doc/scipy/reference/optimize.nonlin.html,但我无法弄清楚如何使用它们。到目前为止我所拥有的是

#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)
你可以帮我一点吗?

1 个答案:

答案 0 :(得分: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]