gpt4 book ai didi

java - Java中BigDecimal的平方根

转载 作者:IT老高 更新时间:2023-10-28 20:25:18 25 4
gpt4 key购买 nike

我们能否仅使用 Java API 而不是定制的 100 行算法来计算 Java 中 BigDecimal 的平方根?

最佳答案

我用过这个,效果很好。 Here's an example of how the algorithm works at a high level.

编辑:我很想知道下面定义的准确度。这是 official source 中的 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 的回答。它更简洁,并且似乎提供了相同或更好的精度。

关于java - Java中BigDecimal的平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13649703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com