javanumerics

Java matrices and numerics


So I just started doing numeric methods in Java;

// I have a matrix class that has get, set methods for creating matrices; have used those in the method below.
// The method below computes a Matrix and prints as well returns it.

public Matrix computeA(){

    int nrows = A.getNumRows();
    int ncols = A.getNumCols();

    for(int i = 0; i < nrows; i++){
        double sum = 0.0;
        for (int j = 0; i< ncols; j++){
                         if (i!=j){
             A.setElement(i,j, aijCalc(i,j) );} // aijCalc is numeric method; setElement has parameters (i, j, value)
        }
    A.print();
    return A;
}

Now, here's what I don't understand how to do: The diagonal where i = j, the matrix entry is 1 - (sum of all the aij entries (for i!=j) in that row). How can I code this in the method above?

My current output(without any rounding off looks like this ):

0.0 0.026055555555555554 0.0248125 0.050694444444444445 0.05872222222222222 0.030208333333333334

-0.0053750000000000004 0.0 0.00792361111111111 0.01813194444444444 0.02361111111111111 0.009874999999999998

-0.0013854166666666667 -0.005291666666666666 0.0 0.008680555555555556 0.009041666666666667 0.0

0.0 0.009041666666666667 0.008680555555555556 0.0 -0.005291666666666666 -0.0013854166666666667

0.009874999999999998 0.02361111111111111 0.01813194444444444 0.00792361111111111 0.0 -0.0053750000000000004

0.030208333333333334 0.05872222222222222 0.050694444444444445 0.0248125 0.026055555555555554 0.0

(it has 0s where i = j)

and it's supposed to look like this:

0.810 0.026 0.025 0.051 0.059 0.030

-­‐0.005 0.946 0.008 0.018 0.024 0.010

-­‐0.001 -­‐0.005 0.989 0.009 0.009 0.000

0.000 0.009 0.009 0.989 -­‐0.005 -­‐0.001

0.010 0.024 0.018 0.008 0.946 -­‐0.005

0.030 0.059 0.051 0.025 0.026 0.810

thanks!


Solution

  • Those extra zeroes are effectively "lies".

    SUGGESTION: Just format the number to a realistic precision (e.g. four or five decimal places).

    EXAMPLE:

    System.out.println (String.format ("%11.2f", x);

    http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

    PS:

    Exactly the same is true of floating-point "printf" just about every other language: including C# and C++.