公式:
核心:求与横坐标交点
求导:
牛顿迭代公式:
特别地:
上述公式求解num的平方根。
Java代码:
public static BigDecimal sqrt(BigDecimal b, BigDecimal eps) {
BigDecimal crt = new BigDecimal(b.toString());
BigDecimal two = BigDecimal.valueOf(2);
int scale = eps.scale() + 2;
Boolean isNegtive = false;
if (crt.compareTo(BigDecimal.valueOf(0)) < 0) {
b = b.negate();
crt = crt.negate();
isNegtive = true;
}
while (true) {
BigDecimal nxt = crt.subtract(crt.multiply(crt).subtract(b).divide(two.multiply(crt), scale, BigDecimal.ROUND_DOWN));
// test
// System.out.println(nxt);
if (nxt.subtract(crt).abs().compareTo(eps) <= 0) {
crt = nxt;
break;
}
crt = nxt;
}
if (isNegtive) {
b = b.negate();
crt = crt.negate();
}
return crt;
}
public static BigDecimal sqrt(BigDecimal b) {
BigDecimal eps = new BigDecimal("0.000000000000000000000000000000000001");
return sqrt(b, eps);
}
public static BigDecimal sqrt(BigInteger b, BigDecimal eps) {
BigDecimal tmp = new BigDecimal(b.toString());
return sqrt(tmp, eps);
}
public static BigDecimal sqrt(BigInteger b) {
BigDecimal tmp = new BigDecimal(b.toString());
return sqrt(tmp);
}