-3

I started learning java yesterday. Since I know other programming languages, it's easier for me to learn Java. It's pretty cool, actually. I still prefer Python :) Anyhoo, I wrote this program to calculate pi based on the algorithm (pi = 4/1 - 4/3 + 4/5 - 4/7....) and I know there are more efficient ways of calculating pi. How would I go about doing this?

import java.util.Scanner;

public class PiCalculator
{
  public static void main(String[] args)
  {
    int calc;
    Scanner in = new Scanner(System.in);
    System.out.println("Welcome to Ori's Pi Calculator Program!");
    System.out.println("Enter the number of calculations you would like to perform:");
    calc = in.nextInt();
    while (calc <= 0){
      System.out.println("Your number cannot be 0 or below. Try another number.");
      calc = in.nextInt();
    }
    float a = 1;
    float pi = 0;
    while (calc >= 0) {
      pi = pi + (4/a);
      a = a + 2;
      calc = calc - 1;
      pi = pi - (4/a);
      a = a + 2;
      calc = calc - 1;
    }
    System.out.println("Awesome! Pi is " + pi);
  }
}

The result of this code, after 1,000,000 calculations is still 3.1415954. There HAS to be a more efficient way of doing this.

Thanks!

6

2 Answers 2

3

The most efficient way to calculate Pi in Java is to not calculate it at all:

System.out.println("Awesome! Pi is " + Math.PI);

Though your question isn't clear about this, my guess is that you are actually trying an exercise. In this case, you could try the Nilakantha series:

float pi = 3;
for(int i = 0; i < 1000000; i += 2) {
    pi += 4 / (float) (i * (i + 1) * (i + 2));
}

Even more efficient and accurate is Machin's formula:

float pi = 4f * (4f * Math.atan(5) - Math.atan(239)) / 5f;
1
  • I agree with this answer. You should mark it as the answer to your question if this is what you were looking for. Feb 4 at 14:12
-1

Why not use Python’s generator expression to implement Leibniz formula for π (one liner :)) :

4*sum(pow(-1, k)/(2*k + 1) for k in range (10000))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.