1

I am trying to solve a system of equations that has 3 variables and a variable number of equations.

Basically, the system is between 5 and 12 equations long, and regardless of how many equations there are, I am trying to solve for 3 variables.

It looks like this:

(x-A)**2 + (y-B)**2 + (z-C)**2 = (c(t-d))**2

I know A,B,C, and the whole right side. A,B,C and the right side are all arrays of length n, where n varies randomly between 5 and 12. So then we have a system of equations that changes in size. I believe I need to use numpy's lstsq function and do something like:

data,data1 = getData()        # I will have to do this for 2 unique systems.
A   = data[:,0]
B   = data[:,1]
C   = data[:,2]
tid = data[:,3]
P = (x-A)**2 + (y-B)**2 + (z-C)**2              
b = tid
solved = lstsq(P,b)
print solved

This however doesn't work, as we know that x,y,z are implicit, and therefore need to be taken out of P in order for this to work. Help!

4

1 回答 1

1

您可能需要的是scipy.optimize.minimize () ,它适用于任意(非线性)方程。numpy.linalg.lstsq() 只解决线性方程组,而且这个问题绝对是非线性的(虽然有一些技术可以线性化方程组,但我认为这不是你想要的)。

一个由 3 个变量组成的 >3 个方程组很可能没有解,因此您必须定义如何衡量给定“解”的好坏,即使它实际上并没有求解方程组。如何将此作为最小化问题取决于您实际尝试执行的物理或问题域解释。一种可能性是,对于以下方程(这是你的稍微重新排列的版本)

(x-A1)**2 + (y-B1)**2 + (z-C1)**2 - T1**2 = 0
(x-A2)**2 + (y-B2)**2 + (z-C2)**2 - T2**2 = 0
...

尝试最小化所有左侧的绝对值之和(如果方程被精确求解,它应该为零)。换句话说,您想要产生以下函数的最小值的 x、y、z

sum( abs( (x-A1)**2 + (y-B1)**2 + (z-C1)**2 - T1**2 ) + abs( (x-A2)**2 + (y-B2)**2 + (z-C2)**2 - T2**2 ) + ... )

代码示例:v是(3,)的ndarray,包含x、y、z;和 A, B, C, tid 是 (N,) 的 ndarrays,其中 N 是方程的数量。

def F(v, A, B, C, tid):
    x = v[0]
    y = v[1]
    z = v[2]
    return numpy.sum( numpy.abs( (x-A)**2 + (y-B)**2 + (z-C)**2 - tid ) )

v_initial = numpy.array([x0, y0, z0]) # starting guesses
result = scipy.optimize.minimize(F, v_initial, args=(A, B, C, tid))
v = result.x
x, y, z = v.tolist() # the best solution found

这应该接近工作,但我还没有测试过。您可能需要一些额外的参数来最小化(),例如方法,tol,...

于 2012-11-27T09:29:12.407 回答