Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program called Compute PI to compute the value of pi, using the followin

ID: 3837914 • Letter: W

Question

Write a program called Compute PI to compute the value of pi, using the following series expansion. You have to decide on the termination criterion used in the computation (such as the number of terms used or the magnitude of an additional term). Is this series suitable for computing pi? pi = 4 times (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 + ellipsis) JDK maintains the value of pi in a double constant called Math.PI. Compare the values obtained and the Math PI, and display the result in percents of Math.PI.

Explanation / Answer

ComputePI.java

import java.util.Scanner;


public class ComputePI {

  
   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       System.out.print("Please input a positive number N: ");
       int n = scan.nextInt();
       while(n <= 0){
           System.out.print("Invalid input. Please input a positive number N: ");
           n = scan.nextInt();
       }
       double sum = 0;
       for(int i=1,j=0;i<=n;i+=2,j++) {
           if(j % 2 == 0){
           sum = sum + 1/(double)i;
           }
           else{
               sum = sum - 1/(double)i;
           }
       }
       double PIValue = 4 * sum;
       System.out.println("PI: "+PIValue);
       System.out.println("Math PI: "+Math.PI);
   }

}

Output:

Please input a positive number N: 100
PI: 3.121594652591011
Math PI: 3.141592653589793

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote