Benito27 de Abril del 2005
Pregunta
hola muchachos! necesito saber si alguien tiene un programa para resolver sistemas de ecuaciones lineales por método de nuestro estimado Gauss. En caso de tenerlo, agradecería q me lo envíen a
[email protected]...
gracias!
Noel Solw27 de Abril del 2005
// program k5a10.CPP - page 83
// for a given matrix float [N][N+1] find the soluction vector
// float x[N] by Gaussian elimination method.
// 7/8/2001
// written in Borland CPP ver 3.1
#include <conio.h>
#include <iostream.h>
#include <iomanip.h>
#include <stdlib.h>
#include <math.h>
#define N 5
void Init(float a[N][N+1],float x[N])
{
randomize();
int i,j;
for(i = 0; i < N; i++)
{
for(j = 0; j < N+1; j++)
a[i][j] = random(21)-10;
x[i] = 0;
}
} // INIT
void ShowSystem(float a[N][N+1],char *msg)
{
for(int i = 0; i < N; i++)
{
cout << setw(15) << msg;
msg[0] = 0;
for(int j = 0; j < N+1; j++)
cout << setw(10) << a[i][j];
cout << endl;
}
cout << endl;
} // SHOW SYSTEM
void Swap(float &a,float &b)
{
float c = a;
a = b;
b = c;
} // SWAP FLOAT
void Pivotting(float a[N][N+1],int k)
{
int index = k;
for(int i = k+1; i < N; i++)
if(fabs(a[i][k]) > fabs(a[index][k]))
index = i;
if(index != k)
for(int j = 0; j < N+1; j++)
Swap(a[index][j],a[k][j]);
} // PIVOTTING
void ErrorExit(float a[N][N+1])
{
ShowSystem(a,"system :");
cout << "singular system - program halts ! ! !" << endl << endl;
exit(0);
} // ERROR EXIT
void Process(float a[N][N+1],float x[N])
{
for(int i = 0; i < N-1; i++)
{
Pivotting(a,i);
if(!a[i][i])
ErrorExit(a);
for(int k = i+1; k < N; k++)
for(int j = i; j < N+1; j++)
a[k][j] -= a[i][j]*a[k][j]/a[i][i];
}
ShowSystem(a,"system :");
for(;i >= 0;i--)
{
x[i] = a[i][N];
for(int j = N-1; j > i;j--)
x[i] -= a[i][j]*x[j];
if(!a[i][i])
ErrorExit(a);
x[i] /= a[i][i];
}
} // PROCESS
void Verification(float a[N][N+1],float x[N])
{
cout << "verification : " << endl << endl;
for(int i = 0; i < N; i++)
{
float sum = 0;
for(int j = 0; j < N; j++)
sum += a[i][j]*x[j];
cout << "x[" << i << "] = " << setw(8) << x[i] << setw(20)
<< sum << setw(9) << " = " << setw(11) << a[i][N] << endl;
}
cout << endl;
} // VERIFICATION
void main()
{
clrscr();
float a[N][N+1],x[N];
Init(a,x);
cout << setprecision(3) << setiosflags(ios::showpoint)
<< setiosflags(ios::fixed);
ShowSystem(a,"system :");
Process(a,x);
Verification(a,x);
cout << "end of program - good bye ! ! !n";
getch();
} // MAIN