我昨天开始学习java。由于我了解其他编程语言,因此学习Java更容易。实际上,这很酷。我还是喜欢Python :) Anyhoo,我写了这个程序来计算基于算法的pi(pi = 4/1 - 4/3 + 4/5 - 4/7 ......),我知道有更有效的方法来计算pi。我该怎么做呢?
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);
}
}
在1,000,000次计算之后,此代码的结果仍为3.1415954。有一种更有效的方法。
谢谢!
答案 0 :(得分:2)
在Java中计算Pi的最有效方法是根本不计算它:
System.out.println("Awesome! Pi is " + Math.PI);
虽然你的问题不明确,但我的猜测是你实际上正在尝试练习。在这种情况下,您可以尝试Nilakantha系列:
float pi = 3;
for(int i = 0; i < 1000000; i += 2) {
pi += 4 / (float) (i * (i + 1) * (i + 2));
}
更高效和准确的是Machin的公式:
float pi = 4f * (4f * Math.atan(5) - Math.atan(239)) / 5f;