Search code examples
javabigdecimalpow

Power doesn't seem to work with BigDecimal (Java)


I have made a little code. So far I just built a do while loop that works with BigDecimal. To be more precise, the counter variable of the loop is a BigDecimal. I already put much effort to it although it might not look like that (it's short).. But that's they first time I work with those numbers.

So in this case the loop will be repeated 25 times. What I wanted do next is using power. I want do 2^counter variable. How can I build this into my code?

import java.math.BigDecimal;
import java.math.*;

public class MiniDecimals {
    public static void main(String[] args){
        BigDecimal bigCount = new BigDecimal("0");
        BigDecimal bigiMax = new BigDecimal("25"); // we stop the loop when we reach 25
        BigDecimal testPow = new BigDecimal("2");
        int res;
        MathContext mc = new MathContext(10);

        do{
            testPow = testPow.pow(bigCount, mc);
            System.out.println(testPow);

            bigCount = bigCount.add(new BigDecimal(1)); 
            res = bigCount.compareTo(bigiMax); 
        }while(res<0);
    }
}

I get error: The method pow(int, MathContext) in the type BigDecimal is not applicable for the arguments (BigDecimal, MathContext)

I have looked this up on the internet already but nothing has helped me so far. Is there a way to do this without changing my code entirely? This is no homework. I'm just trying to learn about big integers and doubles.


Solution

  • The first argument to pow is not a BigDecimal, but rather an int.

    (On a side note, you're aware that testPow will immediately reach and remain at 1, yes?)