Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <math.h>
- using namespace std;
- bool converges(vector < vector <double> > A){
- int N = A.size();
- for(int i = 0; i < N; ++i){
- double sum = 0;
- for(int j = 0; j < N; ++j){
- if(j != i){
- sum += fabs(A[i][j]);
- }
- }
- if(fabs(A[i][i]) <= sum){
- return false;
- }
- }
- return true;
- }
- bool stop(vector <double> x, vector <double> x_prev, double Eps){
- int N = x.size();
- for(int i = 0; i < N; ++i){
- if(fabs(x[i] - x_prev[i]) >= Eps){
- return false;
- }
- }
- return true;
- }
- vector <double> Gauss_Seidel(vector < vector <double> > A, vector <double> b, double Eps){
- int N = A.size();
- vector <double> x(N), x_prev(N);
- do{
- x_prev = x;
- for(int i = 0; i < N; ++i){
- double sum = 0;
- for(int j = 0; j < i; ++j){
- sum += A[i][j] * x[j];
- }
- for(int j = i + 1; j < N; ++j){
- sum += A[i][j] * x_prev[j];
- }
- x[i] = (b[i] - sum) / A[i][i];
- }
- }
- while(!stop(x, x_prev, Eps));
- return x;
- }
- int main(){
- int N;
- cin >> N;
- vector < vector <double> > A(N, vector <double> (N));
- vector <double> b(N);
- for(int i = 0; i < N; ++i){
- for(int j = 0; j < N; ++j){
- cin >> A[i][j];
- }
- cin >> b[i];
- }
- if(!converges(A)){
- cout << "The matrix does not have diagonal predominance!";
- system("PAUSE");
- return 0;
- }
- double Eps = 1e-5;
- cin >> Eps;
- for(auto & x : Gauss_Seidel(A, b, Eps)){
- cout << x << endl;
- }
- system("PAUSE");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement