Linear Equation
LFPS - Forum :: Study Corner :: Computers :: Java :: Snippets
Page 1 of 1
Linear Equation
This doesn't work.....Vinay will repost this Snippet after debugging.
- Code:
import java.io.*;
class Linear_equations
{
public static void main(String args[])
{
int j,i,n;
DataInputStream in=new DataInputStream(System.in);
try
{
System.out.println("What is the size of the system [ n<10 ]");
n=Integer.parseInt(in.readLine());
double x[]=new double[n];
double b[]=new double[n];
double a[][]=new double[n][n];
System.out.println("Enter co-efficients a[i , j] ,row-wise.");
for(i=0;i<n;i++)
{
System.out.println("Row "+(i+1));
for(j=0;j<n;j++)
a[i][j]=Double.valueOf(in.readLine()).floatValue();
}
System.out.println("Input vector b");
for(j=0;j<n;j++)
b[j]=Double.valueOf(in.readLine()).floatValue();
int index[]=new int[n];
x=Gaussian(a,b,index);
System.out.println("Solution vector X ");
for(i=0;i<n;i++)
System.out.println(x[i]+" ");
}
catch(Exception e)
{
System.out.println("Exceptional Error occured! ");
}
}
public static double[] Gaussian(double a[][],double b[],int index[])
{
int n=b.length;
double x[]=new double[n];
gaussian(a,index);
for(int i=0;i<n;++i)
{
for(int j=i+1;j<n;++j)
{
b[index[j]]-=a[index[j]][i]*b[index[i]];
}
}
x[n-1]=b[index[n-1]]/a[index[n-1]][n-1];
for(int i=n-2;i>=0;--i)
{
x[i]=b[index[i]];
for(int j=i+1;j<n;++j)
{
x[i]-=a[index[i]][j]*x[j];
}
x[i]/=a[index[i]][i];
}
order(x,index);
return x;
}
public static void gaussian(double a[][],int index[])
{
int n=index.length;
double c[]=new double[n];
for(int i=0;i<n;++i)
index[i]=i;
for(int i=0;i<n;++i)
{
double c1=0;
for(int j=0;j<n;++j)
{
double c0=Math.abs(a[i][j]);
if(c0>c1)
c1=c0;
}
c[i]=c1;
}
int k=0;
for(int j=0;j<n-1;++j)
{
double pi1=0;
for(int i=j;i<n;++i)
{
double pi0=Math.abs(a[index[i]][j]);
pi0/=c[index[i]];
if(pi0>pi1)
{
pi1=pi0;
k=i;
}
}
int itmp=index[j];
index[j]=index[k];
index[k]=itmp;
for(int i=j+1;i<n;++i)
{
double pj=a[index[i]][j]/a[index[j]][i];
a[index[i]][j]=pj;
for(int l=j+1;l<n;++l)
a[index[i]][l]-=pj*a[index[j]][l];
}
}
}
public static void order(double x[],int index[])
{
int m=x.length;
for(int i=0;i<m;++i)
{
if(index[i]>index[j])
{
int itmp=index[i];
index[i]=index[j];
index[j]=itmp;
double xtmp=x[i];
x[i]=x[j];
x[j]=xtmp;
}
}
}
}
vinays- New LSF Member
- Posts : 6
LFPS - Forum :: Study Corner :: Computers :: Java :: Snippets
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|
Tue Feb 14, 2012 9:02 pm by Sujith
» Kolaveri Di
Tue Nov 22, 2011 5:11 pm by Sujith
» Plane of Remembrance
Mon May 23, 2011 7:44 am by Sujith
» Board Exam Results 2011
Fri May 13, 2011 10:19 pm by Sujith
» Source Code
Wed May 04, 2011 8:06 pm by Sujith
» Rio
Wed May 04, 2011 8:04 pm by Sujith
» Fast and Furious 5
Wed May 04, 2011 7:56 pm by Sujith