# Java高精度运算问题求助

``````//相关性系数计算
public BigDecimal getRelativityTool_bydim(RelativityTool u) {
BigDecimal sim = new BigDecimal("0"); //最后的皮尔逊相关度系数

BigDecimal common_items_len = new BigDecimal(this.rating_map_list.size()); //操作数的个数

BigDecimal this_sum = new BigDecimal("0"); //第一个相关数的和

BigDecimal u_sum = new BigDecimal("0"); //第二个相关数的和

BigDecimal this_sum_sq = new BigDecimal("0"); //第一个相关数的平方和

BigDecimal u_sum_sq = new BigDecimal("0"); //第二个相关数的平方和

BigDecimal p_sum = new BigDecimal("0"); //两个相关数乘积的和

for (int i = 0; i < this.rating_map_list.size(); i++) {
//评分求和                     //平方和                     //乘积和

}
BigDecimal num = common_items_len.multiply(p_sum).subtract(this_sum.multiply(u_sum));
BigDecimal den = sqrt(common_items_len.multiply(this_sum_sq).subtract(this_sum.pow(2)).multiply(common_items_len.multiply(u_sum_sq).subtract(u_sum.pow(2))));
if (den.compareTo(new BigDecimal("0")) == 0) {
sim = new BigDecimal("1");
} else {
sim = num.divide(den,5, BigDecimal.ROUND_HALF_UP);
}
return sim;
}
//大数字开方
public static BigDecimal sqrt(BigDecimal x) {
BigDecimal n1 = BigDecimal.ONE;
BigDecimal ans = BigDecimal.ZERO;
while ((n1.multiply(n1).subtract(x)).abs().compareTo(BigDecimal.valueOf(0.001)) == 1) {
BigDecimal s1 = x.divide(n1, 2000, BigDecimal.ROUND_HALF_UP);
n1 = s2.divide(BigDecimal.valueOf(2), 2000, BigDecimal.ROUND_HALF_UP);

}
ans = n1;
BigDecimal rt = new BigDecimal(ans.toString().split("\\.")[0]);
return rt;
}``````

### 回答：

``````public void test_sqrt() {
BigDecimal x = BigDecimal.valueOf(Long.MAX_VALUE);
BigDecimal x0 = BigDecimal.ZERO;
BigDecimal x2 = new BigDecimal(2);
BigDecimal x1 = new BigDecimal(Math.sqrt(x.doubleValue()));
while (!x0.equals(x1)) {
x0 = x1;
x1 = x.divide(x0, 2000, BigDecimal.ROUND_HALF_UP);