有没有更有效的方法来计算pi?
有没有更有效的方法来计算pi?
我昨天开始学习Java编程语言。由于我知道其他编程语言,所以学习Java对我来说更容易。实际上 Java 还是挺酷的。但是我还是更喜欢 Python :)。不过话说回来,我写了一个计算 pi 值的程序,使用的是 pi=4/1 - 4/3 + 4/5 - 4/7.... 这个算法,但我知道还有更高效的方法。您有什么好的建议吗?
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。我确定一定有更高效的方法。
谢谢!
admin 更改状态以发布 2023年5月21日
在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;