Created
November 30, 2015 07:58
-
-
Save komkanit/1829619d9f79eebd929d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
class Gauss | |
{ | |
static double[,] matrix = {{1.334E-4, 4.123E+1, 7.912E+2, -1.544E+3, -711.5698662}, | |
{1.777, 2.367E-5, 2.07E+1, -9.035E+1, -67.87297633}, | |
{9.188, 0, -1.015E+1, 1.988E-4, -0.9618012}, | |
{1.002E+2, 1.442E+4, -7.014E+2, 5.321, 13824.121}}; | |
static double[,] matrix2 = {{1.334E-4, 4.123E+1, 7.912E+2, -1.544E+3, -711.5698662}, | |
{1.777, 2.367E-5, 2.07E+1, -9.035E+1, -67.87297633}, | |
{9.188, 0, -1.015E+1, 1.988E-4, -0.9618012}, | |
{1.002E+2, 1.442E+4, -7.014E+2, 5.321, 13824.121}}; | |
static int n = 4; | |
public static void Main() | |
{ | |
double[] ans = new double[n]; | |
Console.WriteLine("With out pivot:"); | |
GaussElim(); | |
Cal(ans); | |
PrintAnsElim(ans); | |
Console.WriteLine("With pivot:"); | |
matrix = matrix2; | |
Pivot(); | |
GaussElim(); | |
Cal(ans); | |
PrintAnsElim(ans); | |
} | |
static void PrintAnsElim(double[] ans) | |
{ | |
for(int i=0 ; i<n ; i++) | |
Console.WriteLine("{0}",ans[i]); | |
} | |
static void Print() | |
{ | |
for(int i=0 ;i<n ; i++) | |
{ | |
for(int j=0 ; j<n+1 ; j++) | |
{ | |
Console.Write("{0} ",matrix[i,j]); | |
} | |
Console.WriteLine(); | |
} | |
} | |
static void Pivot() | |
{ | |
for(int i=0 ; i<n ; i++){ | |
for(int j=0 ; j<n ; j++){ | |
if(matrix[i,0]>matrix[j,0]){ | |
for(int k=0 ; k<n+1 ; k++){ | |
Swap(ref matrix[i,k],ref matrix[j,k]); | |
} | |
} | |
} | |
} | |
} | |
static void Swap(ref double a,ref double b) | |
{ | |
double tmp = a; | |
a = b; | |
b = tmp; | |
} | |
static void GaussElim() | |
{ | |
int i,j,k; | |
double a,b; | |
for(j=0 ; j<n-1 ; j++) | |
{ | |
for(i=j+1 ; i<n ; i++) | |
{ | |
a = matrix[i,j]; | |
b = matrix[j,j]; | |
for(k=j ; k<n+1 ; k++) | |
{ | |
matrix[i,k] -=matrix[j,k]*a/b; | |
} | |
} | |
} | |
} | |
static void Cal(double[] ans) | |
{ | |
int i,j; | |
for(i = n-1 ; i>=0 ; i--) | |
{ | |
for(j = n-1 ; j>=i ; j--) | |
{ | |
if(j == i) | |
{ | |
ans[i] = matrix[i,n]/matrix[i,j]; | |
} | |
else | |
{ | |
matrix[i,n] -= matrix[i,j]*ans[j]; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment