ガウス・ザイデル法という解き方。
だんだん解が収束していきます。
4w +1x +2y= 21 2w +5x -1y= 14 1w +3x -7y=-24 w(0)= 5.3 x(0)= 0.7 y(0)= 4.5 w(1)= 2.8 x(1)= 2.6 y(1)= 4.9 w(2)= 2.1 x(2)= 2.9 y(2)= 5.0 w(3)= 2.0 x(3)= 3.0 y(3)= 5.0 w(4)= 2.0 x(4)= 3.0 y(4)= 5.0 w(5)= 2.0 x(5)= 3.0 y(5)= 5.0 w(6)= 2.0 x(6)= 3.0 y(6)= 5.0 w(7)= 2.0 x(7)= 3.0 y(7)= 5.0 w(8)= 2.0 x(8)= 3.0 y(8)= 5.0 w(9)= 2.0 x(9)= 3.0 y(9)= 5.0 w= 2 x= 3 y= 5
public class LinearSystem { public static void main(String[] args){ //右辺の係数 a = new double[][]{ {4, 1, 2}, {2, 5, -1}, {1, 3, -7} }; //左辺値 y = new double[]{ 21, 14, -24 }; //求める値 x = new double[]{ 2, 3, 5 }; //式の表示 String[] ch = {"x", "y", "z"}; for(int i = 0; i < a.length; ++i){ String str = ""; for(int j = 0; j < a[i].length; ++j){ str += String.format(" %" + ((j == 0) ? " " : "+") + "2.0f%s", a[i][j], ch[j]); } System.out.printf("%s=% 2.0f%n", str, y[i]); } //解を計算する double[] s = new double[x.length]; for(int n = 0; n < 10; ++n){//とりあえず10回 for(int i = 0; i < x.length; ++i){ double sum = 0; for(int j = 0; j < x.length; ++j){ if(i == j) continue; sum += a[i][j] * s[j]; } s[i] = (y[i] - sum) / a[i][i]; } for(int j = 0; j < x.length; ++j){ System.out.printf("%s(%d)=% 2.1f ", ch[j], n, s[j]); } System.out.println(); } //準備していた解の表示 for(int i = 0; i < x.length; ++i){ System.out.printf("%s=% 2.0f ", ch[i], x[i]); } System.out.println(); } }