admin管理员组

文章数量:1660164

第六章第十四题(估算PI)(Estimate PI)

  • *6.14(估算PI)PI可以使用下面的数列进行计算:

    编写一个方法,对于给定的i返回m(i),并且编写一个测试程序,显示如下表格:
    i m(i)
    1 4.0000
    101 3.1515
    201 3.1466
    301 3.1449
    401 3.1441
    501 3.1436
    601 3.1433
    701 3.1430
    801 3.1428
    901 3.1427
    *6.14(Estimate PI)PI can be computed using the following summation:

    Write a method that returns m(i) for a given i and write a test
    program that displays the following table:
    i m(i)
    1 4.0000
    101 3.1515
    201 3.1466
    301 3.1449
    401 3.1441
    501 3.1436
    601 3.1433
    701 3.1430
    801 3.1428
    901 3.1427
  • 参考代码:
package chapter06;

public class Code_14 {
    public static void main(String[] args) {
        printTableHead();
        for (int i = 0; i <= 9; i++) {
            System.out.printf("%d\t%.4f\n",i * 100 + 1,ComputePI(i * 100 + 1));
        }
    }
    public static double ComputePI(int i) {
        double pi = 0;
        for (int j = 1; j <= i; j++)
            pi += Math.pow(-1, j + 1) / (2 * j - 1);
        return pi * 4;
    }
    public static void printTableHead() {
        System.out.println("i\tm(i)");
    }
}

  • 结果显示:
i	m(i)
1	4.0000
101	3.1515
201	3.1466
301	3.1449
401	3.1441
501	3.1436
601	3.1433
701	3.1430
801	3.1428
901	3.1427

Process finished with exit code 0

本文标签: 第六章piestimate