Python 如何計算線性方程組 Ax=b 的通解?
試了下 scipy.linalg 的 solve 和 lstsq ,前者直接要求 A 滿秩(可逆),後者似乎也沒法得出通解。
比如 ax=ba = np.array([[2, -2, -4], [-1, 3, 4], [1, -2, -3]])b = np.array([0, 0, 0])
要如何才能得出通解 x 為 c * [1, -1, 1] 呢?
如此即可:
In [1]: import numpy as np
In [2]: a = np.array([[2, -2, -4], [-1, 3, 4], [1, -2, -3]])
In [3]: s, v, d = np.linalg.svd(a)
In [4]: np.compress(v &< 1e-10, d, axis=0)
Out[4]: array([[ 0.57735027, -0.57735027, 0.57735027]]) # 通解
使用sympy,還可以像這樣做:
import sympy
a = sympy.Matrix([[2, -2, -4], [-1, 3, 4], [1, -2, -3]])
b = sympy.Matrix([0, 0, 0])
x = sympy.symarray("x", 3)
print(sympy.solve(a * x - b))
得到結果:
{x_1: -x_2, x_0: x_2}//Fit a line, y = mx + c, through some noisy data-points:
x = np.array([0, 1, 2, 3])
y = np.array([-1, 0.2, 0.9, 2.1])
A = np.vstack([x, np.ones(len(x))]).T
m, c = np.linalg.lstsq(A, y)[0]
print m, c
//Plot the data along with the fitted line:
import matplotlib.pyplot as plt
plt.plot(x, y, "o", label="Original data", markersize=10)
plt.plot(x, m*x + c, "r", label="Fitted line")
plt.legend()
plt.show()
&>&>&> import numpy as np
&>&>&> from scipy import linalg
&>&>&> a = np.array([[3,2,0],[1,-1,0],[0,5,1]])
&>&>&> b = np.array([2,4,-1])
&>&>&> x = linalg.solve(a,b)
&>&>&> x
NumPy-快速處理數據 - 用Python做科學計算
推薦閱讀: