Friday, March 6, 2015

Gaussian ellimination using LU factorization in Java

public double[] gauss(double[][] a,double b[]){

    int n=a.length;
    double[][] p=identity(n);
    double[][] l=identity(n);
    double[][] u=pivot(a,p);
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if(u[i][j]!=0){
                l[i][j]=u[i][j]/u[j][j];
                u[i]=multiplyAndSumLines(u[j],u[i],-l[i][j]);
            }
        }
    }
    double[] y=new double[n];
    double[] z=multiply(p,b);
    double s;
    for (int i = 0; i < n; i++) {
        s=0;
        for (int j = 0; j < i; j++) {
            s+=l[i][j]*y[j];
        }
        y[i]=(z[i]-s)/l[i][i];
    }
    double[] x=new double[n];
    for (int i = n-1; i >= 0; i--) {
        s=0;
        for (int j = n-1; j > i; j--) {
            s+=u[i][j]*x[j];
        }
        x[i]=(y[i]-s)/u[i][i];
    }
    return x;
}

public double[][] pivot(double[][] a, double[][] p) {

    double[][] acopy=copy(a);
    for (int i = 0; i < a.length; i++) {
        int imax=jMaxOf(getColumn(acopy,i),i);
        if(imax!=i){
            double temp;
            for (int j = 0; j < a.length; j++) {
                temp=p[i][j];
                p[i][j]=p[imax][j];
                p[imax][j]=temp;

                temp=acopy[i][j];
                acopy[i][j]=acopy[imax][j];
                acopy[imax][j]=temp;
            }
        }
    }
    return acopy;
}

This is part of the Matrices project.Refer to Basic matrix calculations in Java for the missing secondary methods.

No comments: