我们可以计算平方根BigDecimal仅使用的Java API而不是定制的100线算法在Java中?
Answer 1:
我用这个和它的作品相当不错的。 下面是该算法如何工作在较高水平的例子。
编辑:我很好奇,想看看到底有多精确,这是定义如下。 这里给出一个从所述的sqrt(2) 官方来源 :
(first 200 digits) 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147
在这里它是使用的方法,我下面概述SQRT_DIG等于150:
(first 200 digits) 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206086685
第一偏差后的精度195位发生。 在你自己的风险,如果您需要这样的高精确度,因为这使用。
更改SQRT_DIG 1000产生的精度1570位 。
private static final BigDecimal SQRT_DIG = new BigDecimal(150);
private static final BigDecimal SQRT_PRE = new BigDecimal(10).pow(SQRT_DIG.intValue());
/**
* Private utility method used to compute the square root of a BigDecimal.
*
* @author Luciano Culacciatti
* @url http://www.codeproject.com/Tips/257031/Implementing-SqrtRoot-in-BigDecimal
*/
private static BigDecimal sqrtNewtonRaphson (BigDecimal c, BigDecimal xn, BigDecimal precision){
BigDecimal fx = xn.pow(2).add(c.negate());
BigDecimal fpx = xn.multiply(new BigDecimal(2));
BigDecimal xn1 = fx.divide(fpx,2*SQRT_DIG.intValue(),RoundingMode.HALF_DOWN);
xn1 = xn.add(xn1.negate());
BigDecimal currentSquare = xn1.pow(2);
BigDecimal currentPrecision = currentSquare.subtract(c);
currentPrecision = currentPrecision.abs();
if (currentPrecision.compareTo(precision) <= -1){
return xn1;
}
return sqrtNewtonRaphson(c, xn1, precision);
}
/**
* Uses Newton Raphson to compute the square root of a BigDecimal.
*
* @author Luciano Culacciatti
* @url http://www.codeproject.com/Tips/257031/Implementing-SqrtRoot-in-BigDecimal
*/
public static BigDecimal bigSqrt(BigDecimal c){
return sqrtNewtonRaphson(c,new BigDecimal(1),new BigDecimal(1).divide(SQRT_PRE));
}
一定要检查出barwnikk的答案。 它更简洁,看似提供一样好或更好的精度。
Answer 2:
public static BigDecimal sqrt(BigDecimal A, final int SCALE) {
BigDecimal x0 = new BigDecimal("0");
BigDecimal x1 = new BigDecimal(Math.sqrt(A.doubleValue()));
while (!x0.equals(x1)) {
x0 = x1;
x1 = A.divide(x0, SCALE, ROUND_HALF_UP);
x1 = x1.add(x0);
x1 = x1.divide(TWO, SCALE, ROUND_HALF_UP);
}
return x1;
}
这项工作完美! 极快的超过65536位!
Answer 3:
从Java 9,你可以的! 见BigDecimal.sqrt()
Answer 4:
通过使用卡普的技巧,这可以在不只有两行的循环来实现,给32位精度:
public static BigDecimal sqrt(BigDecimal value) {
BigDecimal x = new BigDecimal(Math.sqrt(value.doubleValue()));
return x.add(new BigDecimal(value.subtract(x.multiply(x)).doubleValue() / (x.doubleValue() * 2.0)));
}
Answer 5:
如果你需要找到唯一整数的平方根 -这些都是可以使用的两种方法。
牛顿法 -速度非常快,甚至对1000位的BigInteger:
public static BigInteger sqrtN(BigInteger in) {
final BigInteger TWO = BigInteger.valueOf(2);
int c;
// Significantly speed-up algorithm by proper select of initial approximation
// As square root has 2 times less digits as original value
// we can start with 2^(leng