How can I solve multivariable linear equation in p

2019-04-14 04:12发布

问题:

I have 10,000 variables. for 100 of them, I do know the exact value.

others are given like:

a = 0.x_1 * b + 0.y_2 * c+ 0.z_1 * d + (1 - 0.x_1 - 0.y_1 - 0.z_1) * a
b = 0.x_2 * c + 0.y_2 * d+ 0.z_2 * e + (1 - 0.x_2 - 0.y_2 - 0.z_2) * b

...

q = 0.x_10000 * p + 0.y_10000 * r+ 0.z_10000 * s + (1 - 0.x_10000 - 0.y_10000 - 0.z_10000) * q

yes I know exact value of 0.x_n, 0.y_n, 0.z_n ... (the point of having 0. as a prefix means it is less than 1 while bigger than 0)

How can I solve this in python? I'd really appreciate if you can provide me some example, with simple equations like this :

x - y + 2z =  5
    y -  z = -1
         z =  3

回答1:

(Using numpy) If we rewrite the system of linear equations

x - y + 2z =  5
    y -  z = -1
         z =  3

as the matrix equation

A x = b

with

A = np.array([[ 1, -1,  2],
              [ 0,  1, -1],
              [ 0,  0,  1]])

and

b = np.array([5, -1, 3])

then x can be found using np.linalg.solve:

import numpy as np

A = np.array([(1, -1, 2), (0, 1, -1), (0, 0, 1)])
b = np.array([5, -1, 3])
x = np.linalg.solve(A, b)

yields

print(x)
# [ 1.  2.  3.]

We can check that A x = b:

print(np.dot(A,x))
# [ 5. -1.  3.]

assert np.allclose(np.dot(A,x), b)