package com.zhp.third.雅可比迭代;
import com.zhp.common.Methods;
/**
* @author 郑海鹏
* @since 2014/10/19 11:22
* @email 284967632@qq.com
*/
public class Jacobi {
public static void main(String[] args) {
double[][] matrix = new double[][] { { 10, -2, -1, 3 }, { -2, 10, -1, 15 },
{ -1, -2, 5, 10 } };
double[] result = getResult(matrix);
Methods.round(result); // 对矩阵进行精确到小数点后十位的四舍五入
Methods.print(result);
}
/**
* 求解一个矩阵
*/
public static double[] getResult(double[][] matrix) {
double[] x = new double[matrix.length];
int iteAmount = 0;
while (iteAmount < 24) { // 迭代次数为24次
iteAmount++;
x = iterative(matrix, x);
}
return x;
}
/**
* 雅可比迭代公式
*/
public static double[] iterative(double[][] matrix, double[] x) {
int col = matrix[0].length;
double[] newX = new double[matrix.length];
if (col < 3) {
System.out.println("提示:方程只有一个未知数");
newX[0] = matrix[0][1] / matrix[0][0];
return newX;
}
for (int i = 0; i < newX.length; i++) {
double sum = 0;
for (int j = 0; j < col - 1; j++) {
if (i == j)
continue;
sum += matrix[i][j] * x[j];
}
newX[i] = (matrix[i][col - 1] - sum) / matrix[i][i];
}
return newX;
}
}
本文展示了一个使用Java实现的雅可比迭代法程序,该程序用于求解线性方程组。通过24次迭代逐步逼近方程组的解,并最终输出结果,适用于数值计算与线性代数的学习。

1550

被折叠的 条评论
为什么被折叠?



