Root with BigDecimal

Posted on

Question :

I’m breaking my head to turn a root into a code.

I know it works something like this:

Math.pow(625, (1.0/4)) = raiz 4ª de 625 = 5

My headache is that my data is BigDecimal s

Sting prazoIn = idtText.getText();
BigDecimal prazo = new BigDecimal(prazoIn);

String valorIn = idtText.getText2();
BigDecimal valor = new BigDecimal(valorIn);

BigDecimal umPonto = new BigDecimal(1.0);

//Não sei como fazer com valores BigDecimais
BigDecimal raiz = Math.pow(valor, (umPonto.divide(prazo);


Answer :

Unfortunately, you do not have a solution ready. Converting to another type is a valid option, so you do not have to use BigDecimal . Conversion will cause loss of value, and worse, so naive tests often fail to detect.

Since Java does not provide anything ready, it has to do its own function. Has one in the OS :

public static BigDecimal powerBig(BigDecimal base, BigDecimal exponent) {
    BigDecimal ans = new BigDecimal(1.0);
    BigDecimal k = new BigDecimal(1.0);
    BigDecimal t = new BigDecimal(-1.0);
    BigDecimal no = new BigDecimal(0.0);
    if (exponent != no) {
        BigDecimal absExponent =  exponent.signum() > 0 ? exponent : t.multiply(exponent);
        while (absExponent.signum() > 0){
            ans =ans.multiply(base);
            absExponent = absExponent.subtract(BigDecimal.ONE);
        if (exponent.signum() < 0) {
            // For negative exponent, must invert
            ans = k.divide(ans);
    } else {
        // exponent is 0
        ans = k;
    return ans;

You also have square root option .

It has libraries ready:

Doing so, depending on the size of precision you need, resolves.

public BigDecimal raiz() {
    return new BigDecimal(Math.pow(new BigDecimal(1.172544).floatValue(), (1.0 / 7)));

//retorno 1.022999903326536230707688446273095905780792236328125


Leave a Reply

Your email address will not be published. Required fields are marked *