Search code examples
javabigdecimal

Java Getting the Exact Value from N raised to n


i have this simple problem.

Sample input:

input one 95.123

input two 12

Raising the first input to second input must give the exact value of the power. like this : 548815620517731830194541.8990253434157159735359672218698

I can't get it right.

here is what i have done so far. I think i'm missing something

System.out.println("Input One");
Scanner scanner = new Scanner(System.in);
Double inputOne = scanner.nextDouble();
System.out.println("Input Two");
Double inputTwo = scanner.nextDouble();
Double result = Math.pow(inputOne, inputTwo);
BigDecimal big = new BigDecimal(result);
System.out.println(big);

what am i missing out?


Solution

  • what am i missing out?

    You're using double to start with, and double can't represent 95.123 exactly. You're then using Math.pow with the double values, which will further lose precision. There's no point in converting an already-lossy value to a high-precision value... it can't magically recover the data.

    Just pass a string to the BigDecimal constructor for the first argument, and BigDecimal.pow to do the computation.

    Sample code:

    import java.math.BigDecimal;
    
    public class Test {
    
        public static void main(String[] args) {
            BigDecimal inputOne = new BigDecimal("95.123");
            int power = 12;
            BigDecimal result = inputOne.pow(power);
            System.out.println(result);
        }
    }
    

    Output:

    548815620517731830194541.899025343415715973535967221869852721
    

    (It looks like your expected value is actually truncated... the exact value should definitely end in a 1, as 312 ends in a 1.)