可用于测试服务器CPU性能
import java.math.BigDecimal;
import java.util.Date;
/**
* <p>
* Title:π 圆周率的计算
* </p>
* <p>
* Description:使用java BigDecimal完成圆周率(Chudnovsky公式)的计算。可以指定计算精度和计算参数。
* </p>
*/
public class TestPi {
private BigDecimal result;
public void run(int n, int scale) {
if (System.getProperty("debug") != null) {
System.out.println("n=" + n);
}
BigDecimal upper = new BigDecimal(426880.0000 * Math.sqrt(10005.0000));
upper = upper.setScale(scale, BigDecimal.ROUND_HALF_EVEN);
if (System.getProperty("debug") != null) {
System.out.println("upper=" + upper);
}
BigDecimal downer = BigDecimal.valueOf(0);
for (int i = 0; i <= n; i++) {
BigDecimal d0 = factorial(6 * i).multiply(
new BigDecimal(545140134 * i + 13591409));
BigDecimal d1 = factorial(i);
BigDecimal d2 = pow(d1, 3);
BigDecimal d3 = factorial(3 * i);
BigDecimal d4 = pow(-640320, 3 * i);
BigDecimal d5 = d2.multiply(d3);
BigDecimal d6 = d4.multiply(d5);
BigDecimal d = d0.divide(d6, BigDecimal.ROUND_HALF_EVEN);
downer = downer.add(d);
}
if (System.getProperty("debug") != null) {
System.out.println("downer=" + downer);
}
if (System.getProperty("debug") != null) {
System.out.println("upper.scale = " + upper.scale());
System.out.println("downer.scale = " + downer.scale());
}
result = upper.divide(downer, BigDecimal.ROUND_HALF_EVEN);
if (System.getProperty("debug") != null) {
System.out.println("result.scale = " + result.scale());
}
}
public BigDecimal getResult() {
return result;
}
public static BigDecimal pow(double val, int power) {
return pow(new BigDecimal(val), power);
}
public static BigDecimal pow(BigDecimal val, int power) {
BigDecimal value = BigDecimal.valueOf(1);
for (int i = 1; i <= power; i++) {
value = value.multiply(val);
}
return value;
}
public static BigDecimal factorial(int n) {
BigDecimal value = BigDecimal.valueOf(1);
for (int i = 1; i <= n; i++) {
value = value.multiply(BigDecimal.valueOf(i));
}
return value;
}
public static void main(String[] args) {
// if(args.length < 2){
// System.out.println("usage: " + "java nz-baby.Pi " +
// " 参数(0-无穷大) 精度(1-4294967296)");
// System.out.println("usage: " + "java nz-baby.Pi " +
// " n(0- ) scale(1-4294967296)");
// System.exit(-1);
// }
int n = Integer.parseInt("2000");
int scale = Integer.parseInt("4000");
System.out.println("palgorithm n=" + n + " scale=" + scale);
long l = System.currentTimeMillis();
System.out.println("start:" + new Date(System.currentTimeMillis()));
TestPi p = new TestPi();
p.run(n, scale);
System.out.println("end:" + (System.currentTimeMillis() - l));
System.out.println("result=" + p.getResult());
}
}