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

Write a program that will find the value of PI iteratively. Print the number of

ID: 3804030 • Letter: W

Question

Write a program that will find the value of PI iteratively. Print the number of iterations and the seconds it took to find the result. You should be able to change the number of iterations. (More iterations will take more time to calculate obviously) PI=3.1415922535897423 after 2500000 iterations It took 0.021 seconds to complete this operation You can use any algorithm you like as long as it is an iterative algorithm. The most well-known one is the Leibniz formula for PI. 1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = pi/4. Using summation notation: sigma^infinity_n=0 (-1)^n/2n + 1 = pi/4. For calculating the time, you can use System.nanoTime() method. We had an example of it in the Repetition.java program in the instructor's lecture content.

Explanation / Answer

HI, Please find my implementation.

Please let me know in case of any issue.

public class PISeries {

  

   public static void main(String[] args) {

      

       double piValue = 0;

      

       int lowerTerm = 1;

      

       long start = System.nanoTime();

      

       for(int i=1; i<=2500000; i++){ // iterating from 1 to 2500000

          

           if(i%2 == 1) // if i is odd, then we need to add

               piValue = piValue + 4.0/lowerTerm;

           else

               piValue = piValue - 4.0/lowerTerm;

          

           lowerTerm = lowerTerm + 2;

       }

      

       long end = System.nanoTime();

      

       System.out.println("PI = "+piValue+" after 2500000 iterations");

       System.out.println("It took "+((end-start)/1000000000.0)+" seconds to complete this operation");

   }

}

/*

Sample run:

PI = 3.1415922535897423 after 2500000 iterations

It took 0.016876766 seconds to complete this operation

*/

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