Answer:
See explaination
Explanation:
public class GaussElim{
private static final double eps = 1e-10; % set epsilon value
public static doublic[] fun(double[][] A,double[] b){
int n=b.length; %calculate length of vector b.
for( int j=0;j<n;j++){
int max=j; %find and swap pivot row.
for (int i=j+1;i<n;i++){
if(Math.abs(A[i][j])>Math.abs(A[max][j])){
max=i;
}
}
double[] t1= A[j]; %swap
A[j]=A[max];
A[max]=t1;
double t= b[j]; %swap
b[j]=b[max];
b[max]=t;
if(Math.abs(A[j][j])<=eps){
throw new ArithmeticException("Matrix is singular."); % if matrix A is a singular matrix then throw error.
}
for(int i=j+1;i<n;i++){
double alpha= A[i][j]/A[j][j];
b[i]=b[i]-alpha*b[j];
for(int k=j;k<n;k++){
A[i][k]=A[i][k]-alpha*A[j][k];
}
}
}
double[] x=new double[n]; % back substitution starts here
for(int i=n-1;i>=0;i--){
double sum=0.0;
for(int j=i+1;j<n;j++){
sum=sum+A[i][j]*x[j];
}
x[i]=(b[i]-sum)/A[i][i];
}
return x;
}
public static void main(String[] args){
int n=3;
double[][] A={{1,2,1},{4,2,0},{-1,5,-3}};
double[] b={5,3,21};
double[] x=fun(A,b);
for(int i=0;i<n;i++){
StdOut.println(x[i]);
}
}
}