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!