Java JScience: How to print the whole Real number?

醉酒当歌 提交于 2019-12-13 07:03:05

问题


I wrote some testing code which calculated Pi to whatever thing I wanted it to calculate to. It looks something like this:

public static void piCalculatorMethod1() {
    int iteration = 1000000;

    Real pi = Real.valueOf(0);

    for (int i = 1; i < iteration + 1; i++) {
        Real current = pi;
        Real addendum = Real.valueOf((1/Math.pow(i, 2)));

        pi = current.plus(addendum);
    }

    pi = pi.times(6);

    pi = pi.sqrt();

    System.out.println(pi.toString());
}

Quite unfortunately, the output decides it would look like this:

3.14159169866

I'm quite sure the end value is much more accurate than that, because I've seen what values they are actually adding, and that's much more accurate than that.

How do I get System.out.println to show me the whole Real instead of just the first few digits?


回答1:


You may need to question your assumption about the convergence of the series. This approximation of π relies on Euler's solution to the Basel problem. Empirically, the example below finds the deviation from π2/6 for a number of iteration counts. As you can see, each order of magnitude in the iteration count adds no more than one decimal digit of accuracy.

Code:

Real PI_SQUARED_OVER_6 = Real.valueOf(Math.pow(Math.PI, 2) / 6);
for (int p = 0; p < 7; p++) {
    int iterations = (int) Math.pow(10, p);
    Real pi = Real.valueOf(0);
    for (int i = 1; i < iterations + 1; i++) {
        pi = pi.plus(Real.valueOf(1 / Math.pow(i, 2)));
    }
    System.out.println("10^" + p + ": " + PI_SQUARED_OVER_6.minus(pi));
}

Console:

10^0: 6.44934066848226E-1
10^1: 9.5166335681686E-2
10^2: 9.950166663334E-3
10^3: 9.99500166667E-4
10^4: 9.9995000167E-5
10^5: 9.999950000E-6
10^6: 9.99999500E-7


来源:https://stackoverflow.com/questions/16996421/java-jscience-how-to-print-the-whole-real-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!