import java.util.Random; import java.util.Scanner; public class Lab10 { public static void main(String[] args) { System.out.println(estimatePi(100000)); } /** * Estimates the value of pi using a classical algorithm. The algorithm * is a summation of n terms that is multiplied by the square root of 12. * The summation is from i=0 to n of (-1)^i * 1/((ith odd number) * 3^i) *

* For example, the summation using 3 terms is: *

* 1 - 1/(3*3) + 1/(5*3^2) * * @param n the number of terms to use in the summation */ public static double estimatePi(int n) { double sum = 0; int pow3 = 1; for (int i = 0; i < n; i++, pow3 *= 3) { double t = 1 / ((2*i + 1) * pow3); if (i % 2 == 0) { sum += t; } else { sum -= t; } } return sum * Math.sqrt(12); } }