问题
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