# 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);
``````

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 .

``````public BigDecimal raiz() {