java计算圆周率,自定义小数点后面的位数
package com.andy.math.util;
import java.math.BigDecimal;
public class PITest {
private static int n = 1000000;
public static void main(String[] args) {
Long start = System.currentTimeMillis();
BigDecimal part1 = arctan(57).multiply(new BigDecimal(176));
BigDecimal part2 = arctan(239).multiply(new BigDecimal(28));
BigDecimal part3 = arctan(682).multiply(new BigDecimal(-48));
BigDecimal part4 = arctan(12943).multiply(new BigDecimal(96));
BigDecimal part = part1.add(part2).add(part3).add(part4);
Long end = System.currentTimeMillis();
System.out.println("计算"+n+"位耗时:"+(end-start)+"毫秒");
System.out.println("计算"+n+"位耗时:"+(end-start)+"毫秒");
}
public static BigDecimal arctan(int x){
int n2 = n+2;
BigDecimal result = BigDecimal.ZERO;
BigDecimal xsquare = new BigDecimal(x*x);
BigDecimal bigx = new BigDecimal(x);
BigDecimal temp;
BigDecimal res = BigDecimal.ONE.divide(bigx , n2, BigDecimal.ROUND_HALF_EVEN);
boolean b = true;
for(int i=1;;i+=2){
temp = res.divide(new BigDecimal(i), n2, BigDecimal.ROUND_HALF_EVEN);
if(temp.compareTo(BigDecimal.ZERO)==0){
break;
}
if(b){
result = result.add(temp);
}else{
result = result.subtract(temp);
}
b = !b;
res = res.divide(xsquare, n2, BigDecimal.ROUND_HALF_EVEN);
}
return result;
}
}