Este post es una respuesta a un tema, pero ya que esta, le puede servir a alguien mas...
El programa (la parte mas importante) no es mio, no programo en C#, pero si junte las piezas que están en la pag. de la fuente, lo hice funcionar y modifique la forma en como se toman los datos de los sistemas de ecuaciones (antes era fijo). También cambie alguna cosa de la forma en que se imprimen los resultados.
Esta editado tambien el post, ahora se ven las barras invertidas (que no salen si se pone una sola, en el editor de T! hay que poner 2 barras para que salga una sola).
Para que salga andando, solo hay que copypastear los codigos, guardarlos en un txt y compilar. (mas abajo esta explicado como hacerlo)
Los programas los probé (la ultima vez, antes use otra cosa) con el compilador de windows que trae .NET framework, el csc.exe (que tiene cualquier PC que tenga intalado .NET, solo hay que buscarlo). Están todos funcionando 100%.
Estos programas encuentran la solución de sistemas de ecuaciones por el método de Gauss-Jordan, funcionan para sistemas de ecuaciones con coeficientes reales (el primero) y para sistemas de ecuaciones lineales con coeficientes complejos (el segundo)
Primer programa: para sistemas de ecuaciones con coeficientes reales.
guardarlo en un archivo de texto con la extensión ".cs", por ejemplo "Gauss-Jordan_reales.cs", compilar y correr
Compilar con:
C:\que\se\yo\donde\esta\el\ejecutable> csc Gauss-Jordan_reales.cs
Ejecutar con:
C:\que\se\yo\donde\esta\el\ejecutable>Gauss-Jordan_reales
Sistema de ecuaciones a probar:
x + y + z = 6,3
x + z = 4,2
x + y = 3,2
Salida por pantalla de todo el desarrollo del programa:
C:\que\se\yo\donde\esta\el\ejecutable>Gauss-Jordan_reales
Cantidad de ecuaciones/variables: 3
Coef(1,1) = 1
Coef(1,2) = 1
Coef(1,3) = 1
Coef(1,4) = 6,3
Coef(2,1) = 1
Coef(2,2) = 0
Coef(2,3) = 1
Coef(2,4) = 4,2
Coef(3,1) = 1
Coef(3,2) = 1
Coef(3,3) = 0
Coef(3,4) = 3,2
Sistema de ecuaciones
| 1 1 1 6,3 |
| 1 0 1 4,3 |
| 1 1 0 3,3 |
Solucion por Eliminacion Gaussiana
X(1) = 1,1
X(2) = 2,1
X(3) = 3,1
Código
using System;
namespace Article_GJE
{
class Program
{
static void Main(string[] args)
{
Console.Write( "\n\nCantidad de ecuaciones/variables: " );
int N_ec = int.Parse( Console.ReadLine() );
double[,] a = new double[N_ec, (N_ec + 1)];
Console.Write( "\n" );
for (int i=0; i<N_ec; i++)
{
for (int j=0; j<(N_ec + 1); j++)
{
Console.Write( string.Format("Coef({0},{1}) = ", (i+1), (j+1) ));
a[i,j] = double.Parse( Console.ReadLine() );
}
}
double [] r = new double[N_ec];
ShowMatrix(a, "\n\nSistema de ecuaciones");
if (LinearEquationsSolver.GaussianElimination(a, r))
ShowSolution(r);
else
Console.WriteLine("\nNo es un sistema de ecuaciones lineales\n");
Console.Read();
}
#region formated output
static void ShowMatrix(double[,] a, string Title)
{
Console.WriteLine(Title + '\n');
for (int i = 0; i <= a.GetUpperBound(0); i++)
{
Console.Write('|');
for (int j = 0; j <= a.GetUpperBound(1); j++)
{
Console.Write(ToStringSign(a[i, j]));
}
Console.Write(" | \n");
}
Console.WriteLine('\n');
}
static void ShowSolution(double[] r)
{
Console.WriteLine("Solucion por Eliminacion Gaussiana\n");
for (int i = 0; i <= r.GetUpperBound(0); i++)
{
Console.Write( string.Format("X({0}) = {1} \n", i+1, r[i]));
}
Console.WriteLine("\n");
}
static private string ToStringSign(double v)
{
if (v < 0) return ' ' + v.ToString(); else return " " + v.ToString();
}
#endregion
}
}
namespace Article_GJE
{
class LinearEquationsSolver
{
/// <summary>
/// GaussianElimination()
/// Gaussian elimination is a method for solving matrix equations
/// By Harvey Triana
/// </summary>
/// <param name="a"> The matrix</param>
/// <param name="r"> The solution array</param>
/// <returns>Success function</returns>
public static bool GaussianElimination(double[,] a, double[] r)
{
double t, s;
int i, l, j, k, m, n;
try
{
n = r.Length - 1;
m = n + 1;
for (l = 0; l <= n - 1; l++)
{
j = l;
for (k = l + 1; k <= n; k++)
{
if (!(Math.Abs(a[j, l]) >= Math.Abs(a[k, l]))) j = k;
}
if (!(j == l))
{
for (i = 0; i <= m; i++)
{
t = a[l, i];
a[l, i] = a[j, i];
a[j, i] = t;
}
}
for (j = l + 1; j <= n; j++)
{
t = (a[j, l] / a[l, l]);
for (i = 0; i <= m; i++) a[j, i] -= t * a[l, i];
}
}
r[n] = a[n, m] / a[n, n];
for (i = 0; i <= n - 1; i++)
{
j = n - i - 1;
s = 0;
for (l = 0; l <= i; l++)
{
k = j + l + 1;
s += a[j, k] * r[k];
}
r[j] = ((a[j, m] - s) / a[j, j]);
}
return true;
}
catch
{
return false;
}
}
}
}
Segundo programa: para sistemas de ecuaciones con coeficientes complejos.
(guardarlo en un archivo de texto con la extension ".cs", por ejemplo "Gauss-Jordan_cmplx.cs", compilar y correr
Compilar con:
C:\que\se\yo\donde\esta\el\ejecutable> csc Gauss-Jordan_cmplx.cs
Ejecutar con:
C:\que\se\yo\donde\esta\el\ejecutable>Gauss-Jordan_cmplx
Sistema de ecuaciones a probar:
x * (2 + i) + y * (-1 - i) = 0 + i
x * (1 + i) + y * (2 + 3i) = 0 - 2i
Salida por pantalla de todo el desarrollo del programa:
C:\que\se\yo\donde\esta\el\ejecutable>Gauss-Jordan_cmplx
Cantidad de ecuaciones/variables: 2
Re[Coef(1,1)] = 2
Im[Coef(1,1)] = 1
Re[Coef(1,2)] = -1
Im[Coef(1,2)] = -1
Re[Coef(1,3)] = 0
Im[Coef(1,3)] = 7
Re[Coef(2,1)] = 1
Im[Coef(2,1)] = 1
Re[Coef(2,2)] = 2
Im[Coef(2,2)] = 3
Re[Coef(2,3)] = 0
Im[Coef(2,3)] = -2
Sistema de ecuaciones
|(2, 1) (-,1 -1) (0, 7) |
|(1, 1) (2, 3) (0, -2) |
Solucion por eliminacion Gaussiana
X(1) = (1, 2)
X(2) = (-1, -1)
Código
using System;
namespace Article_GJE
{
class Program
{
static void Main(string[] args)
{
Console.Write( "\n\nCantidad de ecuaciones/variables: " );
int N_ec = int.Parse( Console.ReadLine() );
ComplexNumber[,] a = new ComplexNumber[N_ec, (N_ec + 1)];
Console.Write( "\n" );
for (int i=0; i<N_ec; i++)
{
for (int j=0; j<(N_ec + 1); j++)
{
double real;
double imag;
Console.Write( string.Format("Re[Coef({0},{1})] = ", (i+1), (j+1) ));
real = double.Parse( Console.ReadLine() );
Console.Write( string.Format("Im[Coef({0},{1})] = ", (i+1), (j+1) ));
imag = double.Parse( Console.ReadLine() );
a[i,j] = C(real, imag);
}
}
ComplexNumber[] r = new ComplexNumber[N_ec];
ShowMatrix(a, "\n\nSistema de ecuaciones");
if (LinearEquationsSolver.GaussianElimination(a, r))
ShowSolution(r);
else
Console.WriteLine("No es un sistema de ecuaciones lineales");
Console.Read();
}
static ComplexNumber C(double Real,double Imaginary)
{
return new ComplexNumber(Real, Imaginary);
}
#region formated output
static void ShowMatrix(ComplexNumber[,] a, string Title)
{
Console.WriteLine(Title + '\n');
for (int i = 0; i <= a.GetUpperBound(0); i++)
{
Console.Write('|');
for (int j = 0; j <= a.GetUpperBound(1); j++)
{
Console.Write(a[i, j].ToStringGaussian() + ' ');
}
Console.Write("| \n");
}
Console.WriteLine("\n");
}
static void ShowSolution(ComplexNumber[] r)
{
Console.WriteLine("Solucion por Eliminacion Gaussiana\n");
for (int i = 0; i <= r.GetUpperBound(0); i++)
{
Console.Write( string.Format("X({0}) = ", i+1));
Console.WriteLine(r[i].ToStringGaussian());
}
Console.WriteLine("\n");
}
#endregion
}
}
/*
* ComplexNumber Class
* By Harvey Triana
*/
namespace Article_GJE
{
using System;
public class ComplexNumber
{
// members
private double m_Real;
private double m_Imaginary;
// constructor
public ComplexNumber()
{
m_Real = 0;
m_Imaginary = 0;
}
public ComplexNumber(double Real, double Imaginary)
{
m_Real = Real;
m_Imaginary = Imaginary;
}
// properties
public double Real
{
get { return m_Real; }
set { m_Real = value; }
}
public double Imaginary
{
get { return m_Imaginary; }
set { m_Imaginary = value; }
}
// Equal method
public bool Equals(ComplexNumber a)
{
return (m_Real == a.Real && m_Imaginary == a.Imaginary);
}
// Let method
public void Let(ComplexNumber a)
{
m_Real = a.Real;
m_Imaginary = a.Imaginary;
}
// Absolute value of a complex number
public double Abs()
{
return (Math.Sqrt(m_Real * m_Real + m_Imaginary * m_Imaginary));
}
// Argument of a complex number in radians
public double Arg()
{
double r = 0;
if (m_Real != 0) r = Math.Atan(m_Imaginary / m_Real);
return (r);
}
// Argument of a complex number in degree
public double ArgDeg()
{
return (180 / Math.PI) * this.Arg();
}
// overridden ToString to return format: a + bi
public override string ToString()
{
string r;
if (m_Real >= 0)
r = ' ' + m_Real.ToString();
else
r = m_Real.ToString();
if (m_Imaginary >= 0)
r += " + " + ImaginaryToString(m_Imaginary);
else
r += " - " + ImaginaryToString(-m_Imaginary);
return r + "i";
}
string ImaginaryToString(double v)
{
if (v == 1) return ""; else return v.ToString();
}
// ToString Gaussian to return format: (a, b)
public string ToStringGaussian()
{
return string.Format("({0}, {1})",
m_Real.ToString(), m_Imaginary.ToString());
}
#region OVERLOAD OPERATORS
// overloaded binary + operator
public static ComplexNumber operator +(ComplexNumber a, ComplexNumber b)
{
return C(a.Real + b.Real, a.Imaginary + b.Imaginary);
}
// overloaded unary - operator
public static ComplexNumber operator -(ComplexNumber a)
{
return C(-a.Real, -a.Imaginary);
}
// overloaded binary - operator
public static ComplexNumber operator -(ComplexNumber a, ComplexNumber b)
{
return C(a.Real - b.Real, a.Imaginary - b.Imaginary);
}
// overloaded binary * operator
public static ComplexNumber operator *(ComplexNumber a, ComplexNumber b)
{
return C(a.Real * b.Real - a.Imaginary * b.Imaginary,
a.Real * b.Imaginary + b.Real * a.Imaginary);
}
// overloaded binary / operator
public static ComplexNumber operator /(ComplexNumber a, ComplexNumber b)
{
double c1, c2, d;
d = b.Real * b.Real + b.Imaginary * b.Imaginary;
if (d == 0)
{
return C(0, 0);
}
else
{
c1 = a.Real * b.Real + a.Imaginary * b.Imaginary;
c2 = a.Imaginary * b.Real - a.Real * b.Imaginary;
return C(c1 / d, c2 / d);
}
}
#endregion
//shortcut to return new ComplexNumber ...
static ComplexNumber C(double r, double i) {return new ComplexNumber(r, i);}
}
}
namespace Article_GJE
{
class LinearEquationsSolver
{
/// <summary>
/// GaussianElimination()
/// Gaussian elimination is a method for solving matrix equations
/// By Harvey Triana
/// </summary>
/// <param name="a"> The matrix</param>
/// <param name="r"> The solution array</param>
/// <returns>Success function</returns>
public static bool GaussianElimination(ComplexNumber[,] a, ComplexNumber[] r)
{
ComplexNumber t = new ComplexNumber();
ComplexNumber s = new ComplexNumber();
int i, l, j, k, m, n;
try
{
n = r.Length - 1;
m = n + 1;
for (l = 0; l <= n - 1; l++)
{
j = l;
for (k = l + 1; k <= n; k++)
{
if (!(a[j, l].Abs() >= a[k, l].Abs())) j = k;
}
if (!(j == l))
{
for (i = 0; i <= m; i++)
{
t.Let(a[l, i]);
a[l, i].Let(a[j, i]);
a[j, i].Let(t);
}
}
for (j = l + 1; j <= n; j++)
{
t = (a[j, l] / a[l, l]);
for (i = 0; i <= m; i++) a[j, i] -= t * a[l, i];
}
}
r[n] = a[n, m] / a[n, n];
for (i = 0; i <= n - 1; i++)
{
j = n - i - 1;
s.Real = 0;
s.Imaginary = 0;
for (l = 0; l <= i; l++)
{
k = j + l + 1;
s += a[j, k] * r[k];
}
r[j] = ((a[j, m] - s) / a[j, j]);
}
return true;
}
catch
{
return false;
}
}
}
}
Bueno, eso es todo por ahora.
Espero les haya gustado el aporte.
Espero les haya gustado el aporte.
Dejate aunque sea un comentario!