Знаходження коренів систем лінійних рівнянь методом Гаусса, методом Зейделя та методом простих ітерацій

Автор: Пользователь скрыл имя, 17 Марта 2012 в 12:47, курсовая работа

Описание работы

Линейная алгебра – часть алгебры, изучающая векторные (линейные) пространства и их подпространства, линейные отображения (операторы), линейные, билинейные, и квадратичные функции на векторных пространствах.
Линейная алгебра, численные методы – раздел вычислительной математики, посвященный математическому описанию и исследованию процессов численного решения задач линейной алгебры.

Содержание

ВВЕДЕНИЕ…………………………………………………………………………5
1 ПОСТАНОВКА ЗАДАЧИ…………………………………………………......…6
2 ТЕОРЕТИЧЕСКАЯ ЧАСТЬ………………………………………………......….7
2.1 Разрешимость системы линейных уравнений…………………………7
2.2 Метод Гаусса…………………………….……………………..…….…..8
2.3 Метод простых итераций………………………………………………13
2.4 Метод Зейделя…………………………………………………………. 18
ВЫВОДЫ……………………………………………………………………......…21
ПЕРЕЧЕНЬ ССЫЛОК…………………………………………………

Работа содержит 1 файл

Курсова робота.doc

— 863.00 Кб (Скачать)

                                          cin >> n;

                                          if (n<2) {

                                                        STOP = false;

                                                        cout << "Уравнений должно быть не менее двух!\n";

                                          }

                                          else STOP = true;

                            } while (STOP == false);

              ///====================== ввод колва коэфициентов ===========================

                            do {

                                          cout << "Введите количество коэффициентов в каждом уравнении: ";

                                          cin >> m;

                                          if (m<2) {

                                                        STOP = false;

                                                        cout << "Коэффициентов должно быть не менее двух!\n";

                                          }

                                          else STOP = true;

                            } while (STOP == false);

 

                            double **matr = Create (n,m);

                            double *mas = new double [n];

                            Fill (matr, n, m);

                            PrintMatr (matr, n, m);

                            Change(matr, mas, n);

                            PrintMatr (matr, n, m);

                            PrintResult(mas, n);

              }

}

 

SI.h

 

#include "stdafx.h"

#include <stdio.h>

#include <iostream>

#include <math.h>

using namespace std;

 

namespace SimpIter

{

              //===================== преобразование матрицы ========================================

              bool Change (double **coefficients, double *rightPart, int cor, int n)

              {

                            bool result = false;

                            int i, row = cor;

                            double temp;

                            // для матрицы 1x1 ответом является ненулевость ее единственного элемента

                            if (cor == n-1)

                            {

                                          result = coefficients[cor][cor]!=0;

                            }

                            else {

                                          while (!result && row<n)

                                          {

                                                        if (coefficients[row][cor] != 0)

                                                        {

                                                                      if (row != cor)

                                                                      {

                                                                                    for (i=0; i<n; i++)

                                                                                    {

                                                                                                  temp = coefficients[cor][i];

                                                                                                  coefficients[cor][i] = coefficients[row][i];

                                                                                                  coefficients[row][i] = temp;

                                                                                    }               

                                                                                    temp = rightPart[cor];

                                                                                    rightPart[cor] = rightPart[row];

                                                                                    rightPart[row] = temp;                   

                                                                      }

                                                                      result = Change (coefficients, rightPart, cor+1, n);

                                                                      if (result)

                                                                      {

                                                                                    break;

                                                                      }

                                                        }

                                                        row ++;

                                          }

                            }

                            return result;

              }

 

              //===================== получение корней системы методом итераций ========================================

              int iteration (double **coefficients, double *rightPart, int n, double *solution, double precision)

              {

                            bool result;

                            int i, j, step=1;

                            double *tempSolution = new double[n];   

                            result = Change(coefficients, rightPart, 0, n);   

                            if (result)

                            {

                                          double fault = precision+1;

                                          for (i=0; i<n; i++)

                                          {

                                                        for (j=0; j<n; j++)

                                                        {

                                                                      if (i != j)

                                                                      {

                                                                                    coefficients[i][j] = - coefficients[i][j] / coefficients[i][i];

                                                                      }

                                                        }

                                                        rightPart[i] = rightPart[i] / coefficients[i][i];

                                                        coefficients[i][i] = 0;

                                          }

                                          for (i=0; i<n; i++)

                                          {

                                                        solution[i] = rightPart[i];

                                          }

                                          while (fault>precision && step<=1000)

                                          {           

                                                        for (j=0; j<n; j++)

                                                        {

                                                                      tempSolution[j] = 0;

                                                        }

                                                        for (i=0; i<n; i++)

                                                        {

                                                                      for (j=0; j<n; j++) 

                                                                      {

                                                                                    tempSolution[i] = tempSolution[i] + coefficients[i][j] * solution[j];

                                                                      }

                                                                      tempSolution[i] = tempSolution[i] + rightPart[i];

                                                        }

 

                                                        fault = 0.0;

                                                        for (j=0; j<n; j++)

                                                        {

                                                                      fault = fault + (solution[j] - tempSolution[j])*(solution[j] - tempSolution[j]);

                                                        }

                                                        fault = sqrt( fault );

                                                        for (j=0; j<n; j++)

                                                        {

                                                                      solution[j] = tempSolution[j];

                                                        }

                                                        step++;

                                          }

                            }

                            else

                            {

                                          step = 1001;

                            }

                            delete tempSolution;

                            return step;

              }

 

              //===================== нулевая главная диагональ ========================================

              void Zero (double **coefficients, double *rightPart, int n)

              {

                            int i, j, k, J;

                            double Z, X;

                            for (i=0; i<n; i++)

                            {

                                          if (coefficients[i][i] != 0)

                                          {

                                                        for (j=0; j<n; j++)

                                                        {

                                                                      if ((coefficients[j][i] != 0) && (j != i))

                                                                      {

                                                                                    J=j;

                                                                                    Z=coefficients[j][i];

                                                                                    X=coefficients[i][i];

                                                                                    break;                                                       

                                                                      }

                                                        }

                                                        for (k=0; k<n; k++)

                                                        {

                                                                      coefficients[i][k] = coefficients[i][k] - coefficients[J][k]*X/Z;

                                                        }

                                                        rightPart[i]=rightPart[i]-rightPart[J]*X/Z;

                                          }

                            }

                            for (i=0; i<n; i++)

                            {

                                          cout << "\n\n";

                                          for (j=0; j<n; j++)

                                                        cout << coefficients[i][j] << "\t";

                            }

                            cout << "\n\nправая часть: ";

                            for (i=0; i<n; i++)

                                          cout << rightPart[i] << "  ";

              }

 

              void SI()

              {

                            setlocale (LC_ALL, "Rus");

                            int i, j;

                            int size;

                            double precision;

                            cout << "\n\t\tМЕТОД ПРОСТЫХ ИТЕРАЦИЙ\n\n";             

                            bool STOP;

                            do {

                                          cout << "\nвведите размерность матрицы: ";

                                          cin >> size;

                                          if (size<1) {

                                                        STOP = false;

                                                        cout << "матрица должна быть не менее чем 2х2!\n";

                                          }

                                          else STOP = true;

                            } while (STOP == false);

                            double **coefficients = new double *[size];

                            for (i=0; i<size; i++)

                            {

                                          coefficients[i] = new double[size];

                            }

                            double *rightPart = new double[size];

                            double *solution = new double[size];

                            for (i=0; i<size; i++)

                            {

                                          cout << "введите строку " << i+1 << ": ";

                                          for (j=0; j<size; j++)

                                          {

                                                        cin >> coefficients[i][j];

                                          }

                            }

                            cout << "введите правую часть: ";

                            for (j=0; j<size; j++)

                            {

                                          cin >> rightPart[j];

                            }

                            cout << "введите точность решения: ";

                            cin >> precision;

                            Zero (coefficients, rightPart, size);

                            int steps = iteration(coefficients, rightPart, size, solution, precision);

                            if (steps>1000)

                            {

                                          cout << "Решение для этой СЛАУ не существует или не найдено. Попробуйте решить СЛАУ другим методом.";

                            }

                            else {

                                          cout << "Корни системы:\n";

                                          for (j=0; j<size; j++)

                                          {

                                                        cout << "x" << j+1 << " = " <<solution[j] << "\n";

                                          }

                                          cout << "колличество итераниц: " << steps;

Информация о работе Знаходження коренів систем лінійних рівнянь методом Гаусса, методом Зейделя та методом простих ітерацій