import java.util.Scanner;
public class GaussElimination {
public static void main(String args[]){
Scanner in=new Scanner(System.in);
System.out.println("press no of eqn:");
int row = in.nextInt();
int col = row+1;
float mat[][]= new float [row][col];
float x[] = new float [row];
for (int i=0;i<row;i++){
x[i]=0;
}
for(int i=0;i<row;i++){
for (int j=0;j<col;j++){
System.out.println("Press MAT"+(i+1)+(j+1));
mat[i][j]= in.nextFloat();
}
}
for(int i=0;i<row-1;i++){
for(int j=i+1;j<row;j++){
float a = mat[j][i];
float b = mat[i][i];
for(int k=0;k<col;k++){
mat[j][k]=mat[j][k]-mat[i][k]*(a/b);
}
}
}
System.out.println("forward elimination:");
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(mat[i][j]==-0){
mat[i][j]=0;
}
System.out.printf("%.2f\t",mat[i][j]);
}
System.out.println();
}
System.out.println("backward substitution");
for(int i=row-1;i>=0;i--){
float temp =0;
for (int j=0;j<col;j++){
if(j<col-1){
if(j<=i)
temp=mat[i][j]+temp;
else
temp=mat[i][j]*x[j]+temp;
}
else
temp=mat[i][j]/temp;
}
x[i]=temp;
}
System.out.println("completed backward subt:");
System.out.println("\n solutions") ;
for(int i=0;i<row;i++){
System.out.println("X"+(i+1)+"="+x[i]);
}
}
}
No comments:
Post a Comment