SOR方法

#include <stdio.h>
#include <math.h>

#define MAXstep 1000
#define Err 1e-6

double sum(int n, int i, double A[][100], double x[], double b[]);
void SOR(int n, double A[][100], double b[], double x[], double w);
double _max(double a, double b);

int main(){
	
	int n;
	double A[100][100],b[100],x[100];
	double w;

	
	
  	scanf("%d", &n);
  	for(int i = 0; i < n; i++){
    	for(int j = 0; j < n; j++){
        	scanf("%lf", &A[i][j]);
        }
    }
  	for(int i = 0; i < n; i++)		scanf("%lf", &b[i]);
  	for(int i = 0; i < n; i++)		scanf("%lf", &x[i]);
  	scanf("%lf", &w);
	
	SOR(n, A, b, x, w);
	
} 

double sum(int n, int i, double A[][100], double x[], double b[]) {
	double ret=0;
	for (int j=0; j<n; j++) {
		ret += A[i][j] * x[j];
	}
	ret -= b[i];
	return ret;
}

double _max(double a, double b) {
	return a > b ? a : b;
}

void SOR(int n, double A[][100], double b[], double x[], double w){
	double exp = 1.0 + Err;
	int step = 0;
	
    if (w >= 2 | w <= 0)
		return;
	
	while(exp > Err && step < MAXstep){
		exp = 0;
		double x0[100];
		for (int u=0; u<n; u++) {
			x0[u] = x[u];
		}
        for (int i=0; i<n; i ++) {
			x[i] = x[i] - w / A[i][i] * sum(n, i, A, x, b);
			exp = _max(exp, fabs(x[i] - x0[i]) / (1.0 + fabs(x[i])));
//			printf("%lf   ", exp);
		}
		
		step ++;
//		printf("\n%d  ", step);
//		for (int k=0; k<n; k ++) {
//			printf("%lf ", x[k]);
//		}

    }
	if (step < 1000) {
		for (int k=0; k<n; k ++) {
			printf("%lf ", x[k]);
		}
		printf("\n%d", step);
	}

}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值