I'm working on a calculator in order to better learn Java. I've written my own code to calculate powers with BigDecimal parameters. As of now, the code cannot handle fractional powers, such as 2^2.2
. In order to tackle this problem, I want to implement the exponent identity X^(A+B)=X^A*X^B
into my code.
How can I determine whether my BigDecimal parameter op2
has digits to the right of the decimal point, and then determine what the value is? For example, the code will recognize that op2 = 2.2 = 2.0 + 0.2
.
I am aware of the scale()
function of BigDecimal, but I'm unsure of how it works. For instance,
BigDecimal bd = new BigDecimal(2.1);
System.out.println(bd.scale());
> 51
BigDecimal bd = new BigDecimal(2.2);
System.out.println(bd.scale());
> 50
Here is the current code to calculate powers:
public static BigDecimal power(BigDecimal op1, BigDecimal op2)
{
boolean isOp1Zero;
if (op1.compareTo(new BigDecimal(0)) == 0)
isOp1Zero = true;
else
isOp1Zero = false;
int distFromZero = op2.compareTo(new BigDecimal(0));
//x^0 = 1
if (distFromZero == 0)
return new BigDecimal(1);
//0^positive = 0
else if (isOp1Zero && distFromZero == 1)
return new BigDecimal(0);
//non-zero^positive
else if (!isOp1Zero && distFromZero == 1)
{
BigDecimal power = op1;
for (int i = 1; i < op2.intValueExact(); i++)
{
power = power.multiply(op1);
}
return power;
}
//0^negative undefined
else if (isOp1Zero && distFromZero == -1)
throw new IllegalArgumentException("Error - zero to negative power");
//non-zero^negative
else if (!isOp1Zero && distFromZero == -1)
{
BigDecimal power = op1;
BigDecimal op2NoSign = op2.multiply(new BigDecimal(-1));
for (int i = 1; i < op2NoSign.intValueExact(); i++)
{
power = power.multiply(op1);
}
return new BigDecimal(1).divide(power);
}
return null;
}
Any advice appreciated! Thank you.