PDA

Просмотр полной версии : Решение линейных уровнений медотом гаусса и крамера


oleandr
01.05.2009, 19:00
Здравствуйте,я почитал ваш форум и понял что тут сидят норм прогеры :) мб у кого то будет несколько лишних минут, и напишит данную прогу на C#

Заранее благодарю !

Flame of Soul
01.05.2009, 19:53
Решение СЛАУ методом Гаусса
(написано на С, в С# переведете сами, я простыла и с температурой как то лень)
#include "stdio.h"
#include "iostream.h"

// возвращает true если LU-разложение для матрицы,
// состоящей из строк и столбцов с currRowAndColumn п numberOfEquation, было найдено
bool getLUDecomposition( double **matrixU, double **matrixL, int currRowAndColumn, int numberOfEquation ) {
bool result;
int i, k; // переменные циклов
double tempItem; // Вспомогательная переменная
// если текущий элемент на диагонали равен 0 - LU-разложение не найдено
result = ( matrixU[currRowAndColumn][currRowAndColumn] != 0 );
if ( result && currRowAndColumn < numberOfEquation - 1 ) {
// определение новых значений элементов матрицы U
// и получение нового столбца в матрице L
for ( i = currRowAndColumn + 1; i < numberOfEquation; i++ ) {
matrixL[i][currRowAndColumn] = matrixU[i][currRowAndColumn] / matrixU[currRowAndColumn][currRowAndColumn];
tempItem = - matrixL[i][currRowAndColumn];
for ( k = currRowAndColumn; k < numberOfEquation; k++ ) {
matrixU[i][k] = matrixU[i][k] + matrixU[currRowAndColumn][k]*tempItem;
}
}
// рекурсивный вызов
result = getLUDecomposition( matrixU, matrixL, currRowAndColumn + 1, numberOfEquation );
}

return result;
}

void main() {
int i, j;
int size;
double **matrixU, **matrixL;

cout << "Gauss'es method of LU.\nEnter system dimension: ";
cin >> size;

matrixU = new double*;
matrixL = new double*[size];
for ( i = 0; i < size; i++ ) {
matrixU[i] = new double[size];
matrixL[i] = new double[size];
for ( j = 0; j < size; j ++ ){
matrixL[i][j] = ( i == j ? 1 : 0 );
}
}

for ( i = 0; i < size; i ++ ){
cout << "Enter " << i + 1 << " row: ";
for ( j = 0; j < size; j ++ ){
cin >> matrixU[i][j];
}
}

if ( !getLUDecomposition( matrixU, matrixL, 0, size ) ) {
cout << "LU-decomposition for this matrix not found";
}
else {
cout << "L-matrix is:\n";
for ( i = 0; i < size; i ++ ){
for ( j = 0; j < size; j ++ ){
cout << matrixL[i][j] << " ";
}
cout << "\n";
}
cout << "\nU-matrix is:\n";
for ( i = 0; i < size; i ++ ){
for ( j = 0; j < size; j ++ ){
cout << matrixU[i][j] << " ";
}
cout << "\n";
}
}
cout << "\nPress \"Enter\" to continue..." << endl;
getchar();
}

Решение СЛАУ методом Краммера:
[SIZE=1](вроде рабочее, проверяйте сами)
#include <iostream.h>
#include <stdio.h>
#include <math.h>
double DET (unsigned int columns);
bool PROVCOL(unsigned int num, char colNum);
unsigned int Column1(unsigned int num, char colNum);
unsigned int Column0(unsigned int num, char colNum);
double **Matrix;
int n;
main()
{
int i, j;
double mainDET;
cout<<"Vvedite kolichestvo uravneniy "<<endl;
cin>>n;
while (n > 10 || n < 1)
{
cout<<"Vu ne mogete vvesti bol'she 10 ili men'she 1 uravneniya, vvedite esche raz ";
cin>>n;
}

Matrix = (double**) new double[n];
for (i=0; i<= n-1; i++)
{Matrix[i] = new double[n+1];}
for (i = 0; i <= n-1; i++)
for (j = 0; j <= n; j++)
{
cout<<"Vvedite element matricu s koordinatami ("<<i<<","<<j<<") ";
cin>>Matrix[i][j];
}
cout<<"Vasha matrica:\n";
for (i = 0; i <= n-1; i++)
{for (j = 0; j <= n; j++)
cout<<Matrix[i][j]<<"\t";
cout<<endl;
}
mainDET = DET(pow(2,n));
if (mainDET == 0)
{
cout<<"Net resheniy!\n";
}
else
{
printf ("Korni sistemu:\n");
for (i=0; i <= n-1; i++)
printf ("%.3f ", -pow(-1,n+i)*DET(pow(2,i))/mainDET);
printf ("\n");
}
cout<<"Detrmenant sistemu raven: "<<mainDET<<endl;
for (i = 0; i <= (n-1); i++)
delete Matrix[i];
delete Matrix;
cout<<"Vuchisleniya zakonchenu. Spasibo chto vubrali nas!\n";
return 0;
}


double DET (unsigned int columns)
{double det = 0;
int i, numCols = 0, lastFalse, cntr = 0;
for (i=0; i<=n; i++)
{
if (PROVCOL(columns, i))
numCols++;
else lastFalse = i;
}
if ((n - numCols) == 0) det = Matrix[n-1][lastFalse];
else
for (i = 0; i <= n; i++)
if (!PROVCOL(columns, i))
{
columns = Column1(columns, i);
det += pow(-1,(cntr))*Matrix[numCols-1][i]*DET(columns);
columns = Column0(columns, i);
cntr++;
}
return det;
}
bool PROVCOL(unsigned int num, char colNum)
{
_asm
{
xor eax, eax; //в данном случаи обнуляет eax
xor ebx, ebx; //тоже самое но для ebx
mov bl, colNum; //bl=colNum
bt num, ebx; //считываем ebx бит из num в регистр флагов
jnc none; //был перенос(ответ в флаге переноса)? Нет (флаг переноса 0), тогда переход на метку none
inc eax; //увеличить eax
none: //просто метка
}
}
unsigned int Column1(unsigned int num, char colNum)
{
_asm
{
xor eax, eax;
mov al, colNum;
bts num, eax;
}
return num;
}
unsigned int Column0(unsigned int num, char colNum)
{
_asm
{
xor eax, eax;
mov al, colNum;
btr num, eax;
}
return num;
}

oleandr
01.05.2009, 20:03
спасибо большое за быстрый отзыв :) , но если все таки кто нибудь переведет на С# буду очень благодарен

procedure
03.05.2009, 09:49
using System;

namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
int size;

Console.WriteLine("Gauss'es method of LU.\nEnter system dimension: ");
size = int.Parse(Console.ReadLine());

double[,] matrixU = new double[size, size];
double[,] matrixL = new double[size, size];

for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
matrixL[i,j] = (i == j ? 1 : 0);
}
}
for (int i = 0; i < size; i++)
{
Console.WriteLine("Enter " + (i + 1) + " row: ");

for (int j = 0; j < size; j++)
{
matrixU[i,j] = double.Parse(Console.ReadLine());
}
}
if (!getLUDecomposition(ref matrixU, ref matrixL, 0, size))
Console.WriteLine("LU-decomposition for this matrix not found");
else
{
Console.WriteLine("L-matrix is:\n");
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
Console.WriteLine(matrixL[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine("\nU-matrix is:\n");
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
Console.WriteLine(matrixU[i,j] + " ");
}
Console.WriteLine();
}
}

}

static bool getLUDecomposition(ref double[,] matrixU, ref double[,] matrixL, int currRowAndColumn, int numberOfEquation)
{
if (matrixU[currRowAndColumn, currRowAndColumn] == 0
&& currRowAndColumn < (numberOfEquation - 1))
return false;
double temp;

for (int i = currRowAndColumn + 1; i < numberOfEquation; i++)
{
matrixL[i, currRowAndColumn] = matrixU[i, currRowAndColumn] / matrixU[currRowAndColumn, currRowAndColumn];
temp = -matrixL[i, currRowAndColumn];
for (int k = currRowAndColumn; k < numberOfEquation; k++)
{
matrixU[i, k] = matrixU[i, k] + matrixU[currRowAndColumn, k] * temp;
}
}
return getLUDecomposition(ref matrixU, ref matrixL, currRowAndColumn + 1, numberOfEquation);
}
}
}

я даж не запускал. Не знаю что за бурда вышла)

oleandr
04.05.2009, 07:18
спасибо

oleandr
18.05.2009, 17:29
как всегда дотянулся, сам занят курсовой по линейке, времени на эту нет.

Мб есть авантюристы которые перепишут код для C#

рублей за 300 мб кто сделает :)

oleandr
19.05.2009, 20:27
ап