简体   繁体   中英

Leibniz approximation - Java

So, I'm trying to write a program that will approximate PI. I think I have Leibniz's formula in correctly but my numbers are coming up wrong. Can anyone spot whats wrong in my code? Or if its just totally screwed up.

import java.util.Scanner;
public class Pi2 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Number of sentances: ");
    double sent = input.nextDouble();
    double den = 1;
    double LeiPI;
    for(int i = 0;i <= sent;i++)
    {
      double firstden = (1/den);
      double firstVAR = 1 - firstden;
      double secvar = (Math.pow(-1, (sent + 1)) / ((2 * sent) - 1));
      double thirdvar = firstVAR + secvar;
      LeiPI = 4 * thirdvar;
      for(int j = 0;j < i;j++)
      {
        if(i < j)
          den++;
        den++;
      }
      if(i == sent)
        System.out.println(LeiPI);
    }
  }
}

Sorry, it's totally screwed up (your words :o).

Going through your code line-by-line:

double den = 1;
double LeiPI;

You should be adding to LeiPI each time round the for loop. If you aren't doing this, all of your iteration state is in den . You can't be doing this, because you'd have to have initialized LeiPI to do so, owing to definite assignment .

for(int i = 0;i <= sent;i++)

You're actually iterating (sent + 1) times.

{
  double firstden = (1/den);
  double firstVAR = 1 - firstden;

Not clear what you're doing here. There is no 1 - anything in a single term in Leibniz's formula (obviously there is 1 - 1/3 ): everything is just +/- 1 / denominator :

1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = pi/4

Anyway:

  double secvar = (Math.pow(-1, (sent + 1)) / ((2 * sent) - 1));

You've got the right idea here with the -1 and the / ((2 * sent) - 1) , but the numerator should be 1.

  double thirdvar = firstVAR + secvar;
  LeiPI = 4 * thirdvar;
  for(int j = 0;j < i;j++)
  {
    if(i < j)
      den++;
    den++;
  }

As I noted above, you are storing all of your iteration state in den , so all you're actually doing here is increasing den by i - so den is just increasing quadratically according to the triangle numbers.

  if(i == sent)
    System.out.println(LeiPI);

You should print LeiPI outside your loop, having initalized the variable previously.

}

I'd suggest that you forget about all of these extra variables: they just clutter it up and make it harder to read. Just implement the term as you see it in the formula.

The following gives the answer you state for sent == 100 :

double LeiPI = 0;
for (int i = 0; i < sent; i++) {
  LeiPI += 4.0 * Math.pow(-1, i) / (2.0 * i + 1);
}
System.out.println(LeiPI);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM