C语言实现雅克比迭代法求根要有注释
时间: 2024-01-29 10:04:02 浏览: 23
// Jacobian Iteration Method to find roots of a system of equations
#include <stdio.h>
#include <math.h>
#define N 3 // Number of equations
int main()
{
float A[N][N+1], x[N], e, sum; // A is the coefficient matrix and x is the solution vector
int i, j, k, flag;
// Reading the augmented matrix
printf("Enter the augmented matrix:\n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N+1; j++)
{
scanf("%f", &A[i][j]);
}
}
// Reading the error tolerance
printf("Enter the error tolerance: ");
scanf("%f", &e);
// Initializing the solution vector
for (i = 0; i < N; i++)
{
x[i] = 0;
}
// Applying Jacobian Iteration Method
do
{
flag = 0;
for (i = 0; i < N; i++)
{
sum = 0;
for (j = 0; j < N; j++)
{
if (i != j)
{
sum = sum + A[i][j] * x[j];
}
}
// Calculating the solution vector
x[i] = (A[i][N] - sum) / A[i][i];
// Checking for error tolerance
if (fabs(x[i] - A[i][N]) > e)
{
flag = 1;
}
}
} while (flag);
// Displaying the solution vector
printf("\nThe solution vector is:\n");
for (i = 0; i < N; i++)
{
printf("x%d = %f\n", i+1, x[i]);
}
return 0;
}