本文主要是介绍(20200331)Jacobi迭代(C语言),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
参考:
【1】https://blog.csdn.net/sinat_32602421/article/details/83475549
// jacobi.c ://雅克比迭代算法
#define _CRT_SECURE_NO_WARNINGS
#include<math.h>
#include<stdio.h>
#include<stdlib.h>#define dim 10//Jacobi迭代法为整体代换法,n为系数矩阵A的阶数,b为右端常向量,x0为迭代初始值,
// A(n×n)*x0(n×1)=b(n×1)
//MaxNum为最大迭代次数,方程组的解返回在数组x1。
void Jacobi(int n, long double a[dim][dim], long double b[dim], long double x0[dim], int MaxNum, long double *x1)
{// n=dim+1;int i, j, k;long double sum;FILE *fp;//打开名为result的文本文件fp = fopen("result.txt", "w");//把迭代初始值输入到result中for (i = 1; i <= n; i++){fprintf(fp, "%1.12Lf ", x0[i]);//换行}fprintf(fp, "\n");for (k = 1; k <= MaxNum; k++){//Jacobi迭代一次for (i = 1; i <= n; i++){sum = 0.0;for (j = 1; j <= n; j++){if (j != i) sum = sum + a[i][j] * x0[j];x1[i] = -1.0 / a[i][i] * sum + b[i] / a[i][i];}}for (i = 1; i <= n; i++){x0[i] = x1[i];//把每步迭代的结果输入到result中fprintf(fp, "%1.12Lf ", x0[i]);}//换行fprintf(fp, "\n");}//关闭文件fclose(fp);
}//主程序
int main()
{int n, i, MaxNum;long double a[dim][dim], b[dim], x0[dim], x[dim];//方程组的阶数,系数矩阵,右端常向量n = 3;a[1][1] = 20.0; a[1][2] = 2.0; a[1][3] = 3.0;a[2][1] = 1.0; a[2][2] = 8.0; a[2][3] = 1.0;a[3][1] = 2.0; a[3][2] = -3.0; a[3][3] = 15.0;b[1] = 24.0; b[2] = 12.0; b[3] = 30.0;//迭代初始值for (i = 1; i <= n; i++){x0[i] = 1000000;}//最大迭代次数MaxNum = 100;//调用Jacobi迭代法求解过程Jacobi(n, a, b, x0, MaxNum, x);//输出方程组的解for (i = 1; i <= n; i++){printf("x[%d]=%1.12Lf\n", i, x[i]);}getchar();return 0;
}
结果:
这篇关于(20200331)Jacobi迭代(C语言)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!