在C语言中,使用迭代法求解方程组通常涉及以下步骤:
下面是一个简单的示例,展示了如何使用C语言和雅可比迭代法求解一个线性方程组:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// 定义矩阵和向量的结构体
typedef struct {
double **data;
int rows;
int cols;
} Matrix;
typedef struct {
double *data;
int size;
} Vector;
// 创建矩阵
Matrix createMatrix(int rows, int cols) {
Matrix matrix;
matrix.data = (double **)malloc(rows * sizeof(double *));
for (int i = 0; i < rows; i++) {
matrix.data[i] = (double *)malloc(cols * sizeof(double));
}
matrix.rows = rows;
matrix.cols = cols;
return matrix;
}
// 创建向量
Vector createVector(int size) {
Vector vector;
vector.data = (double *)malloc(size * sizeof(double));
vector.size = size;
return vector;
}
// 释放矩阵内存
void freeMatrix(Matrix matrix) {
for (int i = 0; i < matrix.rows; i++) {
free(matrix.data[i]);
}
free(matrix.data);
}
// 释放向量内存
void freeVector(Vector vector) {
free(vector.data);
}
// 雅可比迭代法求解线性方程组
Vector jacobiIteration(Matrix A, Vector b, double epsilon) {
int maxIterations = 1000; // 最大迭代次数
int iterations = 0;
Vector x = createVector(A.cols);
for (int i = 0; i < A.cols; i++) {
x.data[i] = 0.0; // 初始化解向量
}
while (iterations < maxIterations) {
Vector x_new = createVector(A.cols);
for (int i = 0; i < A.rows; i++) {
double sum = 0.0;
for (int j = 0; j < A.cols; j++) {
if (j != i) {
sum += A.data[i][j] * x.data[j];
}
}
sum += A.data[i][i] * x_new.data[i];
x_new.data[i] = (b.data[i] - sum) / A.data[i][i];
}
// 检查收敛性
double maxChange = 0.0;
for (int i = 0; i < A.cols; i++) {
double change = fabs(x_new.data[i] - x.data[i]);
if (change > maxChange) {
maxChange = change;
}
}
if (maxChange < epsilon) {
break; // 收敛
}
x = x_new; // 更新解向量
iterations++;
}
if (iterations == maxIterations) {
printf("Warning: Iteration did not converge within %d iterations.\n", maxIterations);
}
return x;
}
int main() {
// 定义方程组的系数矩阵和常数项向量
Matrix A = createMatrix(3, 3);
A.data[0][0] = 4; A.data[0][1] = -1; A.data[0][2] = 0;
A.data[1][0] = -1; A.data[1][1] = 4; A.data[1][2] = -1;
A.data[2][0] = 0; A.data[2][1] = -1; A.data[2][2] = 4;
Vector b = createVector(3);
b.data[0] = 4;
b.data[1] = 4;
b.data[2] = 4;
// 设置收敛阈值
double epsilon = 1e-6;
// 使用雅可比迭代法求解方程组
Vector x = jacobiIteration(A, b, epsilon);
// 输出结果
printf("The solution is: ");
for (int i = 0; i < A.cols; i++) {
printf("%f ", x.data[i]);
}
printf("\n");
// 释放内存
freeMatrix(A);
freeVector(b);
freeVector(x);
return 0;
}
这个示例展示了如何使用C语言实现雅可比迭代法求解一个3x3线性方程组。请注意,这个示例仅用于演示目的,实际应用中可能需要根据具体问题进行调整和优化。