编写sor迭代法的通用c语言计算程序
时间: 2024-10-21 07:03:22 浏览: 24
SOR(Successive Over-relaxation)迭代法是一种加速求解线性方程组的数值方法,它通过调整迭代步长来提高收敛速度。下面是一个简单的通用C语言程序示例,用于SOR方法,假设我们有一个二维线性系统Ax = b:
```c
#include <stdio.h>
#include <stdlib.h>
#define N 5 // 方程组的大小
#define relaxation_factor 1.5
// 线性方程组矩阵A和右侧向量b的初始化
double A[N][N] = {
{2, 1, 0, 0, 0},
{1, 2, 1, 0, 0},
{0, 1, 2, 1, 0},
{0, 0, 1, 2, 1},
{0, 0, 0, 1, 2}
};
double b[N];
// SOR迭代函数
void sor(double (*matrix)[N], double *vector, double *result, double omega) {
for (int i = 0; i < N; ++i) {
double temp = vector[i];
for (int j = 0; j < N; ++j) {
if (i != j)
temp -= matrix[i][j] * result[j];
}
result[i] = (1 - omega) * temp + omega / matrix[i][i] * b[i];
}
}
// 主函数,设置初始猜测值并运行SOR迭代
int main() {
// 初始化b向量
for (int i = 0; i < N; ++i) {
b[i] = 1;
}
// 设置初始猜测值
double initial_guess[N];
for (int i = 0; i < N; ++i)
initial_guess[i] = 0;
// 迭代直到达到预设精度或其他停止条件
double current_error = 1e9, last_error;
int iterations = 0;
while (current_error > 1e-6 && iterations < 1000) {
sor(A, initial_guess, initial_guess, relaxation_factor);
last_error = current_error;
current_error = 0;
for (int i = 0; i < N; ++i) {
current_error += pow(initial_guess[i] - b[i], 2);
}
current_error = sqrt(current_error);
iterations++;
}
printf("After %d iterations, the approximate solution is:\n", iterations);
for (int i = 0; i < N; ++i) {
printf("x[%d] = %.4f\n", i, initial_guess[i]);
}
return 0;
}
阅读全文