Search code examples
javabigdecimal

BigDecimal adding in java


I am trying to add together several large numbers to make a weighted fraction. If there are three numbers going into the fraction(a, b, c), the weighted fraction should be : (1/a)/((1/a)+(1/b)+(1/c))

For now I am only trying to correct the denominator portion of the fraction. The sorted array is {{15 9 13},{15 18 16},{9 18 12},{13 12 16},{17 24 25}}

I am trying to use a big decimal since double and float don't seem to capture the very small fraction that results from weighting. However even with the big decimal, the print out is still 0. What am I doing wrong?

public static BigDecimal[][] weights(int[][]sorted, int k){
    BigDecimal [][] weighted = new BigDecimal[sorted.length][k]; //k=3
    BigDecimal denom = BigDecimal.ZERO;   
    for (int i = 0; i<sorted.length; i++){ //sums to create denominator value
        for(int j = 0; j<sorted[i].length; j++){
            denom = denom.add(new BigDecimal(1/sorted[i][j]));
            System.out.println("denom " + denom);
        }
    }

    return weighted;
}

Any help would be greatly appreciated!!


Solution

  • Even with BigDecimals, you are still performing integer division before the value even goes into the BigDecimal, with 1/sorted[i][j]. Integer division in Java must result in another int, so 1 divided by any positive int 2 or greater will result in 0.

    Use the double literal 1.0 to force floating-point arithmetic.

    1.0 / sorted[i][j]
    

    Then you'll find that BigDecimal is unnecessary and a double denom will work well.