Question

I have the following very simple code that is supposed to iteratively change the values of a matrix (finalvals)until the row sums and column sums approach certain values (given by b1 and c) -

  double[] rowsums = new double[3];
    double[] colsums = new double[3];
    Double[][] finalvals = {
        {10320289.32d,15531663.71d,513718885.9d},
            {5741307.806d,19279894.22d,254573082.9d},
            {216919827.7d,229857986.8d,8769234962d}
    };
    Double[] b1 = {544169638d,273919997d,9217088452d};
    Double[] c = {232981430d,264669549d,9537527108d};
    for(int k = 0;k<1000;k++){
        for(int i = 0;i<3;i++){
            for(int j = 0;j<3;j++){
                rowsums[i] = rowsums[i] + finalvals[i][j];
            }
        }
        for(int i = 0;i<3;i++) {
            for(int j = 0;j<3;j++) {
                finalvals[i][j] = b1[i] * finalvals[i][j] / rowsums[i];
            }
        }
        for(int i = 0;i<3;i++) {
            for(int j = 0;j<3;j++) {
                colsums[j] = colsums[j] + finalvals[i][j];
            }
        }
        for(int i = 0;i<3;i++) {
            for(int j = 0;j<3;j++) {
                finalvals[i][j] = c[j] * finalvals[i][j] / colsums[j];
            }
        }
    }
    for(int i = 0;i<3;i++) {
        for(int j = 0;j<3;j++) {
            System.out.print(finalvals[i][j] + " ");
        }
        System.out.print("\n");
    }

However, the due to numerical leaks, the values of finalvals just become all zeros after a thousand iterations. Is there any way to plug these leaks? Edit: A description of the algorithm - we want the matrix rows to sum to the arrays b1 and matrix columns to sum to array c. So, first distribute the first value of b1 among the first three rows of the matrix in proportion of the existing values and similarly for the other two rows. Then we do the same using the columns and the array c. We do this iteratively many times and we should finally get a matrix whose rows and columns sum appropriately.

Was it helpful?

Solution 2

Ok, I figured it out. The reason was actually not rounding errors at all, but my code was wrong. I should have been setting the rowsums and colsums to zero after every iteration of the k loop. Thanks for every ones help.

OTHER TIPS

If your algorithm gives excessive rounding errors, the solution should be to find a better algorithm, rather than to use higher precision numerics. This looks like a classic linear programming or simultaneous equation problem, for which there are tried and tested algorithms that work well. You need to sit down and study a bit on numerical methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top