javadoubleprecisionbigdecimalautoboxing

BigDecimal output does not contain precise decimal values?


Practice problem using BigDecimal for the first time. My main method output should be:

Area of circle with radius 8.5949958is: 232.081671383290563028029402608911005665488497019210725540793500930304148269265220664195247142820189371870652494944664567810832522809505462646484375

Area of circle with radius 3.440393959403938E7is: 3718483500498323.66662697460176592346057689232315135847190735857072463126614392248114882022491656243801116943359375

however, that's not what is printed. I get a value of

232.081671383290555535978683110442943871021270751953125

for circle one, and a value of 3718483500498323.563695 for circle two. A colleague informed me that I need to use BigDecimals for every value in order to for the output to be precise, but I'm under the impression that I'm already doing this.

import java.math.BigDecimal;
public class Circle
{
private BigDecimal radius = new BigDecimal("0.0");

public Circle()
{
   setRadius(0.0);
} 
public void setRadius(double r)
{
   this.radius = new BigDecimal(r);
}
public BigDecimal findCircleArea(double radius)
{
  this.setRadius(radius);
  BigDecimal Pi = new BigDecimal("3.14159");
  BigDecimal rad = new BigDecimal(Math.pow(radius, 2.0));
  BigDecimal a = Pi.multiply(rad);

  return a;
}

}

Merge if you need to, but I've looked around and haven't been able to find an answer, it's really frustrating me.


Solution

  • I think you might have misunderstood your task or you missed something in the input data. I can prove it easily on a mathematical basis.

    Consider your first example: on the input you have a value equal to 8.5949958. Even without doing multiplication of this number on itself (square) we can estimate a maximum number of digits in its fractional part: it can not be more than 14 digits, because 10^-7 * 10^-7 = 10^-14. If we will take it as a BigDecimal value and square it, we receive:

    BigDecimal rad = BigDecimal.valueOf(radius).pow(2);
    

    =73.87395280201764 which is the exact value of square of the given input. I.e. there is no lose of precision here.

    Going to the next step. Next, you multiply this number on 3.14159. Again, using the same approach we can estimate the maximum number of digits in the meaningful fractional part: it can not be more than 19 digits, because 10^-5 * 10^-14 = 10^-19. Let's do this multiplication:

    BigDecimal a = Pi.multiply(rad);

    =232.0816713832905976476 - 19 digits. So we didn't lose any precision here.

    From what follows that this long numbers, which you expect as an output, simply can not be received for the given input. Or you are missing something in the input, or this is a mistake in the task.