雅可比迭代

本文展示了一个使用Java实现的雅可比迭代法程序,该程序用于求解线性方程组。通过24次迭代逐步逼近方程组的解,并最终输出结果,适用于数值计算与线性代数的学习。


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;
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值