close

這個主題也是個人非常想要實現的功能之一,不過要解聯立方程式的方法有蠻多種的。

像是加減代入消去法、行列運算、克拉瑪法則或是LU分解法等等…。

思考了很久,也參考了很多書籍跟網路上的資訊,個人感覺用行列運算的方式比較符合電腦運算的邏輯

也比較符合個人想實現擴展成N階都能使用的方法

既然選定了行列運算(高斯消去法),就開始來實作囉。

邏輯上是使用係數矩陣做行列運算化為「行梯陣式」,最後再化為「簡化行梯陣式」就可以了。

先舉個例子…,來解下面的聯立方程式…。

$\left\{\begin{matrix} 3x&+ &4y &+ &5z &+ &6a &= &113 \\ 2x&+ &3y &+ &5z &+ &7a &= &123 \\ x&+ &y &+ &z &+ &a &= &38 \\ 5x&+ &2y &+ &2z &+ &3a &= &78 \end{matrix}\right.$

先化成矩陣表示式,並把順序排序一下…※聯立方程式上下整列調整是不影響結果的。

$$\begin{bmatrix} \left.\begin{matrix} 5& 2& 2&3 \\ 3& 4& 5&6 \\ 2& 3& 5&7 \\ 1& 1& 1&1 \end{matrix}\right| \begin{matrix} 78\\ 113\\ 123\\ 38\\ \end{matrix} \end{bmatrix}$$

化為行梯陣式,得到一個上三角矩陣。

$$\begin{bmatrix} \left.\begin{matrix} 5& 2& 2&3 \\ 0& 2.8& 3.8&4.2 \\ 0& 0& 1.214285714&2.5 \\ 0& 0& 0&-0.05882 \end{matrix}\right| \begin{matrix} 78\\ 66.2\\ 39.78571\\ 15.23529\\ \end{matrix} \end{bmatrix}$$

將主對角線上元素化為1

$$\begin{bmatrix} \left.\begin{matrix} 1& 0.4&0.4&0.6 \\ 0& 1& 1.357142857&1.5 \\ 0& 0& 1&2.058823529 \\ 0& 0& 0&1 \end{matrix}\right| \begin{matrix} 15.6 \\ 23.64285714\\ 32.76470588\\ -259\\ \end{matrix} \end{bmatrix}$$

再將主對角線之外的元素按照剛剛的方式消去可以得到最後我們預期想要的矩陣,即所謂簡化行梯矩陣…

$$\begin{bmatrix} \left.\begin{matrix} 1& 0&0&0 \\ 0& 1&0&0 \\ 0& 0& 1&0 \\ 0& 0& 0&1 \end{matrix}\right| \begin{matrix} 87 \\ -356\\ 566\\ -259\\ \end{matrix} \end{bmatrix}$$

相關演算法在wiki上面就有,因此就不再現醜,野人獻曝囉。

以大小為的矩陣來說,高斯消去法的時間複雜度為,方陣則為

嗯,大概是這樣囉。

arrow
arrow

    haruka 發表在 痞客邦 留言(0) 人氣()