程序:
package pai; import java.math.BigDecimal; public class ComplexPi { BigDecimal result; public ComplexPi(int count) { result=new BigDecimal(0); for(int i=1;i<=count;i++) { result=result.add(getAddedPart(i)); } } private BigDecimal getAddedPart(int n) { BigDecimal retval=new BigDecimal(1).divide(new BigDecimal(2*n-1), 20, BigDecimal.ROUND_HALF_UP); if(n % 2==0) { retval=retval.multiply(new BigDecimal(-1)); } return retval; } public String getPi() { return result.multiply(new BigDecimal(4)).toString(); } public static void main(String[] args) { ComplexPi cp=new ComplexPi(100000); System.out.println(cp.getPi()); } }
输出:
3.14158265358979349008
另一个程序:
package pai; public class SimplePiComputer { public static void main(String[] args) { double piDivideByFour = 0; for(int i = 1;i <= 100000;i++) { piDivideByFour += Math.pow(-1, i+1) / (2 * i - 1); } System.out.println("The PI is " + piDivideByFour * 4); } }
结果:
The PI is 3.1415826535897198
参考网页: