Question

I'm trying to approoximate pi using the Leibniz series and the question I got is:

"You can approximate π by using the following series:

 pi = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ((-1)^i+1)/2i - 1

Write a program that displays the π value for i = 10,000, 20,000, ..., to 100,000"

Now the question itself is fairly vague, and that's mainly what I want help with, so far I've gotten to here.

public class Q2 {

public static void main(String[] args) 
{
    for  (int i = 1; i <= 10000; i++)
    {
       double pi = 4* (1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) +
              (Math.pow((-1),(i+1)) ) / ((2*i)-1));

       if(i%10000==0)
        {
            System.out.println();
        }
    }
}

}

The problem is that when run the system produces no result, if ran with an extra else statement to check the vallue of pi it gives back variations on 4.000200030004501 and 3.999799949987497.

 if(i%10000==0)
 {
 System.out.println();
 }
 else
 {
 System.out.print(pi);
 }

Am I augmenting i incorrectly? I feel like theres an aspec to the question that's staring in my face and I'm missing it! Thanks, Dave.

Was it helpful?

Solution

you misunderstood the the series in the question. what they mean is that the i-th element of the series is given by:

((-1)^i+1)/(2i - 1)  [i starting with 1 in this notation]

so the series up until element 2 is:

4 * ( -1^(1+1) / (2*1-1)   +   -1^(2+1) / (2*2-1)   ) = 4*(1 - 1/3)

so the question lists the 1st 6 elements in the series, but the series is infinite in length. that means that for a given value of i (TARGET) the calculation would look like:

double sum = 0;
for (int i=1; i<TARGET; i++) {
   double element = Math.pow(-1,i+1) / (2*i + 1); //element i
   sum += element; // add element i to the results so far
}
double result = 4*sum;

see wikipedia for a more details description of this series (note, the wikipedia article starts counting at i=0)

OTHER TIPS

not sure whether this question is still relevant, but probably the answer could be like it

public class Calculate_PI 
{ 
   public static void main(String[] args)
  {
    double pi = 0;      

    for(int i = 10_000; i <= 100_000; i += 10_000)
    {
        double variablePart = 0;
        for(int j = 1; j <= i; j++)
        {
            variablePart += (Math.pow(-1, j+1) / ((2 * j) - 1));
        }
        pi = 4 * variablePart;
        System.out.printf("For i = %d\npi = %12.9f\n", i,pi);
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top