在以下示例中,我不明白doCalculatePi的含义或作用:

  public static double doCalculatePi(final int sliceNr) {
    final int from = sliceNr * 10;
    final int to = from + 10;
    final int c = (to << 1) + 1;
    double acc = 0;
    for (int a = 4 - ((from & 1) << 3), b = (from << 1) + 1; b < c; a = -a, b += 2) {
        acc += ((double) a) / b;
    }
    return acc;
}

public static void main(String args[]){
    System.out.println(doCalculatePi(1));
    System.out.println(doCalculatePi(2));
    System.out.println(doCalculatePi(3));
    System.out.println(doCalculatePi(4));
    System.out.println(doCalculatePi(10));
    System.out.println(doCalculatePi(100));
    }


我已经打印了值以了解结果是什么,但是我仍然不知道此代码将计算出什么。循环内部的条件不清楚。

最佳答案

我的猜测是它近似于PI

PI = doCalculatePi(0)+doCalculatePi(1)+doCalculatePi(2)+...


只是一个猜测。

试试这个

double d = 0;
for(int k = 0; k<1000; k++) {
    System.out.println(d += doCalculatePi(k));
}


给我

3.0418396189294032
3.09162380666784
3.1082685666989476
[...]
3.1414924531892394
3.14149255348994
3.1414926535900394

10-06 06:53