Search code examples
javaprecisionbigdecimal

Getting much higher precision with BigDecimal (or another class) in Java


I want to compute numbers with arbitrarily long decimal values (suppose I want to take a 100 decimal digits for a particular number).

//Take the square root of 2 for 100 digits in total.
public class Main {
    public static void main(String[] args) {
        BigDecimal root2 = new BigDecimal(Math.pow(2, 0.5));
        root2 = root2.setScale(99, BigDecimal.ROUND_HALF_UP);
        System.out.println(root2);
    }
}

And this program outputs:

1.414213562373095145474621858738828450441360473632812500000000000000000000000000000000000000000000000

Having a beginner background in the storage of bytes, I realize the issue here is either the output format, or the fact that I'm still not getting the precision I'm looking for since it doesn't use the memory I'm expecting it to. Any suggestions? Is it possible to get precision this high? I'm not against turning to Mathematica.

For clarification: I'm trying to get the full precision of 100 digits (the zeros do not belong here).


Solution

  • Here is an explanation why what you are doing is not working.

    Math.pow() returns a double. So your code is calculating the value using the precision provided by double, and then creating a BigDecimal from that double. It's too late to set the precision on the big decimal since it only has the double as input.

    So you can not use Math.pow() for your purpose. Instead you need to find another library that does arbitrary precision calculations.

    Refer to this question for more: Java's BigDecimal.power(BigDecimal exponent): Is there a Java library that does it?