0

I have a matrix populated by double values (from 0 to 1). For convenience, let's talk about rows and columns. I want to normalize the double values of the matrix, so that the sum of all the rows, for each columns, returns 1. This task triggers a floating point precision issue since, using double, the sum will never return 1. So I tried using BigDecimalbut the result slightly differs.

Here is my code:

    double[][] U = new double[6][1015];
    double[] sumPerCol = new double[db.size()+1];
    for(int i=0; i<U.length; i++){
        for(int j =0; j<U[i].length; j++){
            double x = new Random().nextDouble();
            U[i][j] = x;
            sumPerCol[j] += x;
        }
    }
    double[] sumPerCol2 = new double[db.size()+1];
    for(int i=0; i<U.length; i++){
        for(int j =0; j<U[i].length; j++){
            BigDecimal x = new BigDecimal(U[i][j],MathContext.DECIMAL128);
            BigDecimal tot = new BigDecimal(sumPerCol[j],MathContext.DECIMAL128);
            BigDecimal x2 = x.divide(tot,MathContext.DECIMAL128);
            U[i][j] = x2.floatValue();
            sumPerCol2[j] += U[i][j];
        }
    }
    for(double d : sumPerCol2){
        System.out.println(d);
    }

For sure, I'm not using BigDecimal properly. Can anyone help?

Roberto
  • 243
  • 1
  • 5
  • 15
  • If you really want precision, you can use BigDecimal, but don't mix them with doubles. But even for BigDecimal, division **can't** always produce exact results. – Rudy Velthuis Jul 27 '16 at 11:14

1 Answers1

0

You are right that you cannot safely use == on double values. But you probably will not need that. Normalizing the matrix only requires to divide each element by the sum of the respective column elements. If you want to check for normalization, just sum up the elements and check whether the difference to 1 is "very small" (you can define an epsilon value, say 10^(-10).

I do not see any reason for using BigDecimal here. If for some reason, you really need absolute precision, use an appropriate implementation of rational numbers (fractions).

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142