0

I'm doing code for my class that require to output the area, circumference, and the number of digits in both the area and circumference for a circle. The output is not supposed to be rounding up or down, but just calculate all the way out, however my code is not doing this properly. This is my code:

    circumference = 2 * pi * radius;
    area = pi * Math.pow(radius, 2);
    digitString1 = Double.toString(circumference);
    digitString2 = Double.toString(area);

    int count1 = 0;
    for (int i = 0, len = digitString1.length(); i < len; i++) {
        if (Character.isDigit(digitString1.charAt(i))) {
            count1++;
        }
    }

    int count2 = 0;
    for (int i = 0, len = digitString2.length(); i < len; i++) {
        if (Character.isDigit(digitString2.charAt(i))) {
            count2++;
        }
    }

    System.out.println("The Circumference is: " + circumference);
    System.out.println("The Area is: " + area);
    System.out.println("Total number of digits in the circumference is: " + count1);
    System.out.println("Total number of digits in the area is: " + count2);
}

When I input 11 for example, I get:

    Circles selected. Please enter the radius: 11
    The Circumference is: 69.11503837897544
    The Area is: 380.132711084365
    Total number of digits in the circumference is: 16
    Total number of digits in the area is: 15

Instead of the correct output:

    Circles selected. Please enter the radius: 11
    The circumference is: 69.11503837897544
    The area is: 380.1327110843649
    Total number of digits in the circumference is: 16
    Total number of digits in the area is: 16

See how the ...649 at the end of the area rounded up to ...65. Can someone please help? Thanks!

NexGenSlayer
  • 9
  • 1
  • 2
  • 4
    Are you sure that `380.1327110843649` and `380.132711084365` are distinct double-precision floating-point values? (Are you aware that floating-point values have only a finite amount of precision, and can't represent all values exactly?) – ruakh Oct 11 '16 at 00:28
  • You're worried about a .0000000000001 difference? – resueman Oct 11 '16 at 00:36
  • Actually, sorry, they are indeed distinct values: http://ideone.com/QewUAe. But of course, the calculations you're doing are not infinitely precise, and so can result in roundoff error even above the threshold you can detect. – ruakh Oct 11 '16 at 00:42
  • 2
    I'd like to see how you define `pi` that "is not supposed to be rounding up or down" :) – Alexei Levenkov Oct 11 '16 at 00:43
  • I am curious about the "number of digits" output. The number of digits in the output is going to be related to the number of digits in your approximation to PI. Use the first million digits and you are likely to get around a million digits in the output. – Patricia Shanahan Oct 11 '16 at 01:26

0 Answers0