Basically I wrote a method for reciprocal value of a BigDecimal instance:
public class Main{
public static void main(String[] args) {
BigDecimal value1 = new BigDecimal("88");
BigDecimal reciproc1 = reciproc(value1);
BigDecimal reciproc2 = reciproc(reciproc1);
System.out.println("Initial value: " + value1);
System.out.println("Reciproc1: " + reciproc1);
System.out.println("Reciproc2: " + reciproc2);
}
public static BigDecimal reciproc(BigDecimal value) throws ArithmeticException{
if (value.equals(new BigDecimal("0"))){
throw new ArithmeticException("Cannot divide by zero");
}
return new BigDecimal("1").divide(value, 20, RoundingMode.HALF_UP);
}
}
The output will be like:
Initial value: 88
Reciproc1: 0.01136363636363636364
Reciproc2: 87.99999999999999997185
It's obvious that variable reciproc2 must be equal to an initial value. Unfortunately, it's not the case with my method. I've tried to resolve this by manipulating with scale and rounding mode but all my attempts were futile:
return new BigDecimal("1").divide(value, 3, RoundingMode.HALF_UP);
Reciproc2: 90.909
or
return new BigDecimal("1").divide(value, 15, RoundingMode.CEILING);
Reciproc2: 87.9999999999999999999995073